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.
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.
Programmers can use any Python source code as a module by implementing an 'import' statement in another Python program or Python file.
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.
from.. import statement
import whole module
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