1. Creating a Simple Package:
Consider a simple package named my_package
:
my_package/
|-- __init__.py
|-- module1.py
|-- module2.py
The __init__.py
file indicates that the directory should be treated as a package.
2. Module Content in module1.py
:
# module1.py
def add_numbers(a, b):
return a + b
3. Module Content in module2.py
:
# module2.py
def multiply_numbers(a, b):
return a * b
4. Using the Package in Another Script:
You can use the modules from the package in another Python script by importing them.
# main.py
from my_package import module1, module2
# Using functions from module1
result_sum = module1.add_numbers(3, 4)
# Using functions from module2
result_product = module2.multiply_numbers(2, 5)
print(result_sum)
print(result_product)
5. Relative Imports within the Package:
You can use relative imports to refer to modules within the same package.
# Relative import within the package
from . import module2
result_subtract = module2.subtract_numbers(10, 3)
print(result_subtract)
6. Executing Package Module as a Script:
You can check if a module is being run as the main program and execute certain code accordingly.
# Executing module within the package as a script
if __name__ == "__main__":
print("This is executed when the module is run as a script within the package.")
7. Importing Subpackages:
You can import subpackages using dot notation.
# Importing a subpackage
from my_package.subpackage import module3
result = module3.square(5)
print(result)
8. Building and Distributing Packages:
To distribute your package, you can create a setup.py
file and use tools like setuptools
. This allows users to easily install your package.
# setup.py
from setuptools import setup, find_packages
setup(
name='my_package',
version='1.0',
packages=find_packages(),
install_requires=[
# List your dependencies here
],
)
Run the following command to build and distribute your package:
python setup.py sdist
9. Installing the Package:
Users can install your package using pip
.
pip install my_package
10. Conclusion:
Building and importing packages in Python is a powerful way to organize and distribute code. By creating packages, you can structure your projects into modular components, making them more maintainable and shareable. Understanding the process of building, importing, and distributing packages is crucial for collaborating with other developers and contributing to the Python ecosystem.
In the next sections, we’ll explore more advanced topics and practical applications of packages in Python.