Advanced Python -1
A detailed description of python module,package,__init__.py, absolute import and relative import
1 - Module vs Package
In Python, both modules and packages are organizational units that help in structuring and organizing code in larger projects. However, they serve different purposes and have distinct characteristics:
- Module:
- A module in Python is a single file containing Python code.
- It acts as a way to organize Python code, grouping related functions, classes, and variables together.
- Modules allow you to reuse code by importing them into other modules or scripts.
- The file name of a module is used as the module name, without the ‘.py’ extension.
2. Package:
- A package is a way of organizing related modules into a single directory hierarchy.
- A package contains an
__init__.pyfile, which can be empty or may contain initialization code for the package. - Packages can include sub-packages, forming a nested structure of directories and modules.
- Packages are used to organize larger codebases by providing a hierarchical structure.
my_package/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
├── __init__.py
└── module3.py2 - __init__.py
The __init__.py file is used to indicate that a directory should be considered a Python package. This file can be empty, or it can contain Python code that will be executed when the package is imported
Get Srigin Sasidharan’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are some common use cases for the __init__.py file:
i - Package Initialization
The __init__.py file can contain initialization code that is executed when the package is imported. This allows you to perform any setup or configuration needed for the package.
# my_package/__init__.py
print("Initializing my_package")
# Other initialization code can go hereii - Explicit Imports
- You can use the
__init__.pyfile to specify which modules should be imported when someone imports the package. This can make it more convenient for users of the package.
# my_package/__init__.py
from .module1 import *
from .module2 import *
# Now, when users import the package, they can access functions and variables of the module1 and module2iii - Variables and Constants
You can define variables or constants in the __init__.py file that are meant to be used at the package level.
# my_package/__init__.py
PACKAGE_VERSION = "1.0"As we’ve learned about modules and packages, let’s now proceed to build a Python package. In the next part, I will explain how to create a Python package and upload it to PyPI.




