How to import modules and functions in Python?
Tagged: programming, python
- This topic has 0 replies, 1 voice, and was last updated 3 years, 3 months ago by
Santhosh Kumar D.
- AuthorPosts
- May 16, 2020 at 9:14 PM #3222
Santhosh Kumar D
KeymasterModules 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 nametips
can be imported into other Python files or can be used on the Python command-line interpreter using theimport
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, theflask
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 theImportError
.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 calledrandint
from within that module, you can use the following statement.from random import randint
More resources:
Modules – Python documentation - AuthorPosts
- You must be logged in to reply to this topic.