Junior
How to create a package in Python?
sobes.tech AI
Answer from AI
Creating a package in Python involves several steps:
-
Creating the package directory. The directory name will be the package name.
-
Creating the
__init__.pyfile. This file makes the directory a package. It can be empty but is often used for:- Package initialization.
- Defining
__all__for import control. - Importing submodules or objects into the package.
-
Creating modules (
.pyfiles) inside the package directory. Each.pyfile inside the package is a module. -
(Optional) Creating subpackages. Other directories with
__init__.pyfiles inside the main package. -
(Optional) Creating supporting files. For example,
README.md,LICENSE,setup.py.
Example structure:
my_package/
├── __init__.py
├── module_a.py
├── module_b.py
└── sub_package/
├── __init__.py
└── module_c.py
File contents:
#__init__.py
# You can import something from modules directly
from .module_a import my_function_a
__all__ = ['my_function_a'] # Defines what is imported with 'from my_package import *'
#module_a.py
def my_function_a():
print("Hello from module A!")
#module_b.py
def my_function_b():
print("Hello from module B!")
#sub_package/__init__.py
# Import from a module inside the subpackage
from .module_c import my_function_c
#sub_package/module_c.py
def my_function_c():
print("Hello from module C in sub_package!")
Using the package:
# In another file outside the my_package directory
# Import a module
import my_package.module_b
my_package.module_b.my_function_b()
# Import a function directly (if it is in __all__ or explicitly imported in __init__.py)
from my_package import my_function_a
my_function_a()
# Import from a subpackage
from my_package.sub_package import my_function_c
my_function_c()