Python
Python Package
What is a Python Package?
A Python package is a collection of modules that are grouped together in a directory. A package can contain subpackages, modules, and data files. A package is a directory that contains a special file called __init__.py
, which can be empty or contain initialization code for the package.
Creating a Python Package
To create a Python package, you need to create a directory with the package name and add an __init__.py
file to it. You can then add modules to the package by creating Python files in the package directory.
my_package/
├── my_package/ # Package folder
│ ├── __init__.py # Initializes the package
│ ├── module1.py # Your Python module(s)
│ └── module2.py # Additional modules (optional)
├── tests/ # Test directory (optional)
│ ├── test_module1.py # Tests for module1.py
│ └── test_module2.py # Tests for module2.py
├── README.md # Project description
├── setup.py # Build script for setuptools
├── setup.cfg # Optional configuration file
├── LICENSE # License file
└── requirements.txt # Dependencies (optional)
Local Test
Go to the root directory of package (where setup.py is located) and run the following command:
> pip install -e .
Build Package
The Python packaging ecosystem is transitioning towards using pyproject.toml as the central configuration file, as defined in PEP 518. While setup.py
and setup.cfg
are still supported, it’s recommended to adopt pyproject.toml
for future-proofing your project. Tools like Poetry
and the latest versions of setuptools
support configuration via pyproject.toml
.
Before building the package, make sure you have installed the build
package. You can install it using the following command:
> pip install build
To build the package, run the following command:
> python -m build
Publish Package
pip install twine
twine upload dist/*
Use Package
pip install <package_name>