Modules and Packages in Python
Modules and Packages
30
In Python, a module is a file containing a set of functions, classes, or variables that can be imported and used in other Python scripts. A package, on the other hand, is a way of organizing related modules in a hierarchical manner.
To create a module, you simply create a new file with a .py extension and define the functions, classes, and variables you want to include in it. To use the module in another script, you use the import statement followed by the name of the module.
For example:
import my_module # use a function from the module my_module.my_function() # access a variable from the module print(my_module.my_variable)
To create a package, you organize modules into directories and include an init.py file in each directory to indicate that it's a package.
For example:
my_package/ __init__.py module1.py module2.py
To use a module from a package, you use the dot notation to specify the package and module names.
For example:
import my_package.module1 # use a function from the module my_package.module1.my_function() # access a variable from the module print(my_package.module1.my_variable)
In summary, modules and packages are an essential part of Python's modular design, allowing you to organize and reuse code more efficiently.
March 25, 2023