How to Import Modules and Functions in Python

Modules are simply Python .py files containing Python code. Modules can be directly imported into other modules or into the main module. This eliminates the need to copy definitions and statements into each and every file that you code. Any Python file can be referenced as a module.

Importing a module.

For example, if you have a Python file named tips.py, then its module name tips can be imported into other Python files or can be used on the Python command-line interpreter using the import statement.

import tips

The import statement is declared at the top of the code, under any general comments.

Python has many built-in modules that provide standard functionalities. Check the Python Standard Library for the full list of all built-in modules that come with every Python installation.

For example, to import the math module, you can use the following statement.

import math

Since math is a built-in module for providing mathematical functions, it will be directly imported from the Python Standard Library.

For example, flask is another Python module for mico web framework functions. It can be imported similarly.

import flask

Since flask is not a built-in module of Python, you will get the following error.

ImportError: No module named 'flask'

So before importing it, you have to first install it using the Python command-line interpreter. To install a new module, you need to deactivate the Python interpreter using CTRL + D.

And then install the module that you want using the pip command. For example, the flask module can be installed using the following command.
pip install flask

Once installed, you can now import flask into your Python code, and it will execute without the ImportError.

Importing functions from within a module.

You can also import a specific function from within a Python module. You can do so by using the from keyword followed by the name of the module and then the import statement for a specific function from within that module.

For example, random is a built-in module for generating random numbers. To import a specific function called randint from within that module, you can use the following statement.

from random import randint

More resources:
Modules – Python documentation

Leave a Reply

Your email address will not be published. Required fields are marked *