This is an old revision of the document!
How to Create and Publish Your Own Python Package
Prerequisites
Before we start, ensure you have:
- Basic knowledge of Python programming.
- Python 3.6 or higher installed.
- pip installed.
Step 1: Set Up Your Project Structure
A well-organized project structure is crucial, as the intention here is that this is a package that will out live individual projects and be maintained for many years, potentially by multiple teams. You need to ensure you have tests, and clear documentation. Here’s a basic template:
Step 2: Writing Your Package Code
Obviously your package isn’t going to be much use if it doesn’t do anything. I’ve created two basic modules. The first can do addition and subtraction, while the second can do multiplication and division.
Step 3: Creating __init__.py
The __init__.py
file makes Python treat the directory as a package. Create package_publishing/__init__.py
:
# package_publishing/__init__.py from .module1 import add, subtract from .module2 import multiply, divide
Step 4: Writing Tests
Testing ensures your package works as expected. Create tests/test_module1.py
:
# tests/test_module1.py import unittest from package_publishing import add, subtract class TestModule1(unittest.TestCase): def test_add(self): self.assertEqual(add(1, 2), 3) self.assertEqual(add(-1, 1), 0) def test_subtract(self): self.assertEqual(subtract(2, 1), 1) self.assertEqual(subtract(2, 3), -1) if __name__ == "__main__": unittest.main()
Step 5: Creating setup.py
Note: setup.py
is obsolete. Use project.toml
instead. https://packaging.python.org/en/latest/tutorials/packaging-projects/
The setup.py
file is essential for packaging. Create setup.py
:
from setuptools import setup, find_packages setup( name="package_publishing", version="0.1", packages=find_packages(), install_requires=[], author="Andy", author_email="andy@dont_spam_me.co", description="A simple example private package", long_description=open("README.md").read(), long_description_content_type="text/markdown", url="https://github.com/nydasco/package_publishing", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )