Modules in Python are files containing Python code. They allow you to organize code into files for better maintainability, reusability, and to avoid namespace collisions.
.py
file.Example module math_operations.py
:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
import
statement.# main.py
import math_operations
result = math_operations.add(5, 3)
print(result) # Output: 8
Packages are namespaces that contain multiple modules. They allow you to structure your Python project by organizing modules hierarchically.
__init__.py
file inside it. This file can be empty or contain initialization code.Example package structure:
my_package/
│
├── __init__.py
├── module1.py
└── module2.py
# main.py
import my_package.module1
from my_package import module2
result1 = my_package.module1.add(5, 3)
result2 = module2.subtract(5, 3)
print(result1) # Output: 8
print(result2) # Output: 2
Python code can be packaged and distributed for installation using tools like setuptools
and pip
. Packaging involves defining metadata, dependencies, and installation instructions for your project.
setup.py
: This file defines package metadata and dependencies using setuptools
.Example setup.py
:
from setuptools import setup, find_packages
setup(
name='my_package',
version='1.0',
packages=find_packages(),
install_requires=[
'dependency1',
'dependency2',
],
)
Include __init__.py
: Ensure all directories that should be treated as packages have an __init__.py
file.
Build the Package: Use setuptools
to build a distribution package.
python setup.py sdist
pip
.pip install my_package