general summary
In Python, a package is a way to organize related modules.
Packages are directories with a special __init__.py file that indicates they’re Python packages.
mypackage/
\_\_init\_\_.py
module1.py
module2.py
subpackage/
\_\_init\_\_.py
submodule1.py
submodule2.pyFeatures of a package
Modularize Code: Group related functionality.
Encapsulate State: By using underscores (_) in the module names, you can indicate that certain modules or attributes are for internal use.
Control Scope: The __init__.py file can specify the modules to be imported when the package is imported. This can, in a way, control scope.
Package Directories
Packages are directories that contain an __init__.py file. When a directory has an __init__.py file, Python understands it as a package. This mechanism allows for hierarchical structuring of project
What’s Inside __init__.py?
The __init__.py file is optional, but it’s a good practice to have one. It lets you do many things when the package is first imported, such as setting up package-level resources, initializing variables or data, or defining methods that are available as part of the package.
Best Practices
Choose Descriptive Names: Make sure those names aren’t already taken by existing packages on, say, PyPI.
Follow PEP 8 Naming Conventions: Use lowercase names, and heed the guideline to avoid leading underscores.
Use Relative Imports: This is especially important in larger packages with many code files. It ensures your import system doesn’t break if you change the absolute module path.
Use:
from . import module1 from .subpackage import submodule1
Avoid:
from mypackage import module1 # using absolute import