How does library packaging work in Python?
Answer from AI
sobes.tech AI
Python packages are directories containing modules (.py files) and a special __init__.py file. The __init__.py file signals to Python that the directory should be treated as a package. It can be empty or contain code to initialize the package, which runs upon the first import of the package.
Package structure:
package_examples/
__init__.py
module_1.py
module_2.py
subpackage/
__init__.py
module_3.py
Importing is done using dot notation:
# Import the entire package
import package_examples
# Import a specific module from the package
import package_examples.module_1
# Import a specific object from a module
from package_examples.module_1 import class_or_function
# Import all contents of a module (not recommended for production)
from package_examples.module_1 import *
When importing, Python searches for packages and modules in directories listed in sys.path.
The __init__.py file can define __all__, a list of names that will be imported when using from package import *.
# Inside package_examples/__init__.py
__all__ = ["module_1", "subpackage"]
# When using "from package_examples import *", only module_1 and subpackage are imported
When a subpackage is imported, its __init__.py is executed as the main package, as well as the subpackage.
Packages allow organizing code into logical units, avoiding name conflicts, and simplifying code reuse.