Maison > Article > développement back-end > Modules et packages Python : décompression de la réutilisabilité du code
Modules and packages are essential for keeping your code organized, scalable, and modular. Let’s dive deep into how they work, why they matter, and how to create your own.
A module in Python is simply a .py file that contains functions, classes, and variables. Modules allow you to split complex projects into manageable pieces by grouping related code together.
Example:
Let’s create a simple module, math_helpers.py, that contains utility functions for math operations:
# math_helpers.py def add(a, b): return a + b def subtract(a, b): return a - b
To use this module in another file:
# main.py import math_helpers result = math_helpers.add(10, 5) print(result) # Outputs: 15
You can also import specific functions to keep it concise:
from math_helpers import add print(add(10, 5))
A package is a directory that contains multiple related modules. It’s structured with an __init__.py file (often empty) to signal to Python that the directory should be treated as a package. Packages are great for organizing larger codebases.
Example of Package Structure:
my_project/ │ ├── geometry/ │ ├── __init__.py │ ├── shapes.py │ └── areas.py │ └── main.py
Here, geometry is a package containing modules shapes.py and areas.py.
Accessing Package Modules:
# Inside main.py from geometry import shapes, areas
The __init__.py file lets you initialize and customize packages. By including imports or setup code in __init__.py, you control what’s accessible at the package level.
# geometry/__init__.py from .shapes import Circle, Square
This way, when you import geometry, Circle and Square are available without needing to import each submodule individually.
Python’s standard library is packed with built-in modules that simplify common tasks. Here are a few must-know modules:
Example of using the math module:
import math print(math.sqrt(25)) # Outputs: 5.0
For larger projects or reusable code libraries, you can create custom packages and install them locally using pip.
my_custom_package/ ├── my_module.py ├── __init__.py └── setup.py
# setup.py from setuptools import setup, find_packages setup(name="my_custom_package", version="1.0", packages=find_packages())
Thoughts: Modules and Packages, Python’s Secret Weapon for Clean Code
With modules and packages, Python lets you keep your code organized, reusable, and scalable. So, instead of drowning in one big file, break it down, import only what you need, and keep your code clean and efficient.
? Cheers to modular magic!
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!