Python Module | How to use python module in python
Python Module
A module is a file consisting of Python code. A module can define functions, classes, and variables. A module can also include runnable code.
Modules are used to categorize Python code into smaller parts. A module is simply a Python file, where classes, functions, and variables are defined. Grouping similar code into a single file makes it easy to access. Have a look at the below example.
Module Advantage
Reusability: Modules let programmers save source code in files permanently & hence the codes in module files are persistent. Module codes can rerun as many times as required.
Categorization: Similar type of attributes can be placed in one module.
Import Statement
Programmers can use any Python source code as a module by implementing an 'import' statement in another Python program or Python file.
Syntax
When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module.
Example:
add.py file
Example:
Output:
add.py file
sub.py file
div.py file
main.py file
Output:
from.. import statement
math.py file
main.py file
Output:
import whole module
Example:
Output:
Packages in Python
- First, we create a directory and give it a package name, preferably related to its operation.
- Then we put the classes and the required functions in it.
- Finally, we create an __init__.py file inside the directory, to let Python knows that the directory is a package