Your First Python Package: A Beginner’s Guide
Have you ever written a Python script that you think could be really helpful to the community? Packaging your Python code is a great way to make it reusable, shareable, and easy for others to install. This guide will walk you through the process of creating your own Python package in a simple and intuitive way, even if you’re a beginner.
What is a Python package?
A Python package is a collection of Python scripts grouped together to carry out specific tasks. It offers a convenient way to share your code with other Python developers globally by enabling them to install it in their own projects. Packaging your script brings several advantages:
- Organization: Keeps your project neat, structured, and professional.
- Reusability: Allows you to share your code with others or use it across different projects.
To publish a package, you’ll need a PyPI account. The Python Package Index (PyPI) is a repository for Python software, allowing users to find and install software created by the Python community. To create an account, proceed to the link above and sign up on the official PyPI website to register your account.
Getting started
Before writing your package, you need a few basic requirements:
- A Python version (preferably 3.6 or later)
- A PyPI account for publishing your package
- (Optional) An IDE to write your script
It is also essential to install several tools for publishing a package, including the twine python package, which allows your module to be distributed via PyPI. To install twine, simply run the following command in your terminal.
pip install twine
We are going to create a simple package called HelloWriter
.This package will contain a single function, myprint()
, within the printer
module. The function will print "Hello World" if no parameters are passed, and if a parameter is provided, it will print Hello {parameter}
These initial setup steps are a one-time requirement and do not need to be repeated.
Structuring package
Create a folder using your project or repository name. Inside this folder, create a file called setup.py
and leave it empty for now; we’ll return to it shortly. Next, create a subfolder named src
and open it in your preferred IDE. Within the src
folder, create a python file named after the module, for example, printer.py
. This file name will correspond to the module name within your package. Additionally, create an empty __init__.py
file inside the src
folder to signify that it is a package.
HelloWriter/
|
├── src/
| ├── __init__.py
│ └── printer.py
├── setup.py
└── README.md
The setup.py
file is the backbone of your package. It serves as a script for developing and distributing Python packages. It contains metadata like the package name, version, and author details. This data is used by the pip
tool, a package manager that allows users to easily install and manage Python packages through the command line. Running setup.py
with pip
facilitates the building and sharing of your Python package, making it accessible to others.
# setup.py
from setuptools import setup
setup(
name='HelloWriter',
version='0.1',
description='A sample Python package',
author='John',
author_email='john@example.com',
packages=['src'],
)
Create a README.md
file inside your package directory. This will explain what your package does and how to use it. This will also appear on your package’s PyPI page.
# My Package
This is a sample Python package to demonstrate packaging.
## Installation
pip install HelloWriter
Edit the module named printer
. Inside this module, we’ll define a function called myprint()
. This function will have an optional parameter called user
. Its purpose will be to print a greeting message based on whether or not a value is passed to the user
parameter:
- If no value is passed: The function will print “Hello, World!”.
- If a value is passed: The function will customize the greeting to include the given name, such as “Hello, Alice!”.
This step helps modularize and organize the code, making it easy to reuse the myprint()
function in other scripts by simply importing the printer
module.
# printer.py
def myprint(name=None):
if name is None:
print("Hello, World!")
else:
print(f"Hello, {name}!")
We have finished editing out module for now, feel free to add more functions and parameters to check the functionality and play around with it. This gives a basic template for working on the packaging your code. We are now gonna proceed in publishing it.
Publishing package on PyPI
To create a distributable version of your package, run the following command:
python setup.py sdist bdist_wheel
This generates a dist/
directory containing your package files in formats suitable for distribution (source and wheel). Use twine
to upload your package to the Python Package Index (PyPI).
API tokens provide a secure way to authenticate when uploading packages to PyPI. Instead of using your username and password, you can use an API token specific to your account or project. Here’s how to create and use an API token:
- Verify your email address (check your account settings)
- In your account settings, go to the API tokens section and select “Add API token”
PyPI will display the token only once. Copy and store it securely (e.g., in a password manager). When you’re ready to upload your package, replace your PyPI username with _token_
and use the API token as the password:
twine upload dist/* -u _token_ -p <your-api-token>
This token-based authentication ensures secure and streamlined package uploads, without exposing your PyPI credentials. We now have successfully uploaded our package as a distributable version in PyPI. Lets install the same and verify that.
Verification
To verify the installation of your package, install it using the name you provided in the setup.py
file. Run the following command to install your package:
pip install hellowriter
After installation, create a new Python file in a separate folder and use the code below to test the functionality of your package.
# main.py
import printer # Import the printer module
# Call myprint without a parameter
printer.myprint() # Output: Hello, World!
# Call myprint with a parameter
printer.myprint("Alice") # Output: Hello, Alice!
# Call myprint with another name
printer.myprint("Bob") # Output: Hello, Bob!
With the successful completion of our initial package version, we can continue to enhance it by modifying the module code or adding more modules and features. By updating the version number in the setup.py
file, we can make these improvements available to all Python users worldwide.
Conclusion
Congratulations! You’ve successfully created a Python module, added a custom function, and used it in another script. This simple example demonstrates the power and flexibility of Python modules in making your code reusable and organized.
Building and sharing your first Python package is just the beginning. With each update and improvement, you contribute to a global community, making your work more powerful and accessible to developers around the world. Happy contributing 😊