How to Create and Publish a Python Package in 5 Simple Steps
Ever wondered how you could create a package like NumPy? Before you can build the next big thing, you must first understand what's needed to create a package in Python. A package is essentially a collection of files bundled together, containing functions, classes, and other reusable code.
To make things simple, this article will walk you through creating a practical package: a decimal-binary converter. This package will convert decimal numbers to binary and vice versa.
Step 1: Structuring Your Python Package
A Python package isn't just a single file; it's a well-structured collection of several files. Here’s how our decimal-binary converter package will be organized:
decimal_binary_converter/
├── decimal_binary_converter/
│ ├── __init__.py
│ └── converter.py
├── tests/
│ └── test_converter.py
├── pyproject.toml
├── README.md
└── LICENSE
This structure might look a bit overwhelming at first, but let's break it down step by step.
Step 2: Creating the Core Package Files
The __init__.py
File
The first file we need inside our package folder is __init__.py
. This file tells Python that the folder should be treated as a package. While it can be completely empty, it's often used to make imports easier for users of your package.
For our package, let's add the following statement to it:
from .converter import decimal_to_binary, binary_to_decimal
This allows users to import the functions directly from the package like this:
from decimal_binary_converter import decimal_to_binary
Instead of the more verbose alternative:
from decimal_binary_converter.converter import decimal_to_binary
The Main Logic File (converter.py
)
This is the most important file in our package. It's where the actual conversion logic resides. A package can contain multiple files like this, each handling a different piece of functionality.
Let's add the functions that will convert decimal to binary and binary to decimal inside converter.py
:
def decimal_to_binary(decimal_num):
"""Converts a decimal number to its binary representation."""
if not isinstance(decimal_num, int):
raise TypeError("Input must be an integer.")
return bin(decimal_num)[2:]
def binary_to_decimal(binary_str):
"""Converts a binary string to its decimal representation."""
if not isinstance(binary_str, str):
raise TypeError("Input must be a string.")
return int(binary_str, 2)
Step 3: Defining Package Metadata with pyproject.toml
Python packaging is constantly evolving, and pyproject.toml
is now the preferred way to define package metadata and build dependencies. It standardizes package builds, ensuring tools like pip
handle installations consistently across various environments, and it eliminates the need for a separate requirements.txt
file.
Here is how we can define it for our package:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "decimal-binary-converter"
version = "0.0.1"
authors = [
{ name="Example Author", email="[email protected]" },
]
description = "A small example package for decimal and binary conversion"
readme = "README.md"
requires-python = ">=3.7"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[project.urls]
"Homepage" = "https://github.com/pypa/sampleproject"
"Bug Tracker" = "https://github.com/pypa/sampleproject/issues"
This modern approach replaces the older setup.py
file, making our package future-proof and easier to maintain.
Step 4: Adding Documentation and a License
README.md
A good README.md
file is crucial. It helps users understand what your package does and how to use it effectively. It should include installation instructions, usage examples, and any other relevant information.
LICENSE
If you're sharing your package publicly, adding a license is a very good idea. The MIT license is a common and permissive choice. It basically says that anyone can do whatever they want with your code, but you are not liable if something breaks.
Step 5: Testing, Building, and Publishing
Writing Tests
Testing is a critical part of software development. Inside the tests/
folder, we write scripts to check if our package works correctly. This is a fundamental best practice that ensures reliability and makes future updates safer.
Building and Publishing
Once our package is ready, we need to build and publish it.
Install Dependencies: First, we need to install some tools to get started.
bash pip install build twine
Build the Package: Next, we build the source code file and a binary distribution (wheel).
bash python -m build
Upload to PyPI: Finally, we upload it to the Python Package Index (PyPI) to make it available to everyone.
bash twine upload dist/*
And with that, our package is live for the world to use! That's everything you need to know to create your first Python package.
Join the 10xdev Community
Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.