Uploading your Python package to PyPI allows other users to download and use it with pip install.
Ensure your package has a structure similar to this. This is a basic structure but can vary based on specific needs.
your_package_name/
src/
your_package_name/
__init__.py
module1.py
module2.py
sub_package/
__init__.py
module3.py
...
tests/
README.md
LICENSE
setup.py
.gitignore
- your_package_name/: The top-level directory with your package's name.
- src/: Contains your package code. Wrapping it in src/ helps avoid common issues with package imports.
- __init__.py: An empty file indicating that this directory should be treated as a Python package.
- module1.py, module2.py, ...: Your Python modules.
- tests/: Directory for your package's test file
- README.md: A Markdown file with a description, documentation, examples, etc.
- LICENSE: The license file for your package.
- setup.py: A setup script with metadata for your package.
- .gitignore: Specifies untracked files to ignore.
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="...",
version="0.0.1", # major.minor.micro
description="...",
long_description=long_description,
long_description_content_type="text/markdown",
author="...",
author_email="[email protected]",
url="...",
install_requires=["dependency1", "dependency2", ...],
package_dir={"": "src"},
packages=find_packages(where="src"),
classifiers=[ # Choose appropriate classifiers from https://pypi.org/classifiers/
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.10",
)
Create a PyPI account at PyPI Registration. Set up 2FA for security and generate an API key used to upload your package via twine.
Create a .pypirc file in your $HOME (Unix/Linux) or %USERPROFILE% (Windows) directory with the following content:
[pypi]
username = __token__
password = pypi-AgEIcHlwaS5scmcCJD...
Keep this API key confidential.
Install the required tools:
pip install --upgrade setuptools wheel
pip install build
In your package's root directory (where setup.py is located), build your package with:
python -m build
This will create distribution files in the dist/ directory.
Install the required tool:
pip install twine
Before uploading, check the dist/ directory to confirm everything is built correctly. Run the following command from within your package's root directory to upload your package to PyPI:
twine upload dist/*