Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

How to Create Python Packages [2023]

How to Create Python Packages
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Python is the third most-used programming language based on a 2023 Stackoverflow survey. This general purpose can be used in data science, web development, machine learning, software engineering, and scientific computing. 

A Python package is one of the terms you will encounter as you learn and interact with the Python language. What are Python packages, and how can you create some?

This article will;

  • Define Python packages
  • Explain the importance of Python packages in programming
  • Demonstrate how to create Python packages
  • Demonstrate how to use and test Python packages
  • Demonstrate how to upload Python packages

What are Python Packages?

What-are-Python-Packages

Python packages are essential building blocks in programming. Without packages, developers could be writing everything from scratch, making programming a long and stressful process. Python packages are collections of Python modules, basically a collection of reusable code. 

A module in Python is a file containing Python code that can be imported into other Python programs. To create a Python package, you must store the code in a directory that contains a  __init__.py file. 

A Python package can contain other packages (nesting), and thousands of Python packages are available online. Some of these packages are official, while others are not. Most of the Python packages are available on https://pypi.org/

Django, a Python web framework, is an example of a package you can use to build web applications. Scikit-learn, PyTorch, and TensorFlow are popular packages in the machine learning field. 

Importance of Python Packages

Importance-of-Python-Packages

Why not create everything from scratch as a programmer? Do we need Python packages? These are some of the reasons why Python packages are important;

  • Saves time: Python package gives you access to pre-written code that solves common problems. You can use Python packages instead of reinventing the wheel whenever you want to write a Python script. 
  • Makes it easy to distribute code: Collaboration is very common in programming. You can create a Python package that your team members can always import when collaborating on a project. 
  • Code reusability: If there is a code block that you always have to write in your Python programs, you can package it and be importing in your applications. 
  • Code organization: Python packages allow you to organize your code into logical modules. Such an approach makes it easy to read and maintain your Python code. 

How to Create Your First Python Package

How-to-Create-Your-First-Python-Package

We have already stated that Python is a general-purpose language. You can create different types of packages as a programmer.

For instance, you can have a package that automates certain tasks, a package that helps you budget, or even learn a new language. However, before you start creating your first package, you need the following;

Prerequisites;

  • Python is installed on your local machine. If you use Linux, Python is installed with your OS by default. You can use this command python –version or python3 –version to check if Python is installed. If Python is installed, you will see something like this on your terminal;
Python-Version

If you don’t have Python, you can download it at https://www.python.org/downloads/

  • Understanding of Python. You need to understand how to write Python classes, modules, and functions. 
  • A package manager. We will use pip for this demonstration. You can check if pip is installed using this command;
pip --version

If installed, you will see something similar on your terminal. 

pip-version

The requirements may vary depending on the nature of the package you want to install. 

I will create a simple Python package for this demonstration that checks if a number is prime. You can follow along;

  • Step one: Create a project folder. I will name mine as primechecker.
  • Step two: Create another folder inside the primechecker folder and name it prime.
  • Step three: Create a file inside the directory you created in step two, and name it prime.py. You can combine the three steps using this command;
 mkdir primechecker && cd primechecker && mkdir prime && cd prime && touch prime.py
  • Step three: Open your project in your code editor. You can then add this code to the prime.py file that checks if a number is a prime number;
def is_prime(number):

    if number < 2:

        return False

    for i in range(2, int(number ** 0.5) + 1):

        if number % i == 0:

            return False

    return True
  • Step four: Inside the prime folder, create a new file and name it __init__.py. This file makes Python recognize the project folder we created as a package. 

You can use this command;

touch prime/__init__.py
  • Step five: Test your code. We can create a script in a test.py file inside the root folder that checks if a number is prime. Navigate back to the main folder and use this command;
touch test.py

You can then add this code to this file;

from prime.prime import is_prime

number = int(input("Enter a number: "))

result = is_prime(number)

print(f"{number} is prime: {result}")

Run this command to check your code;

python3 test.py

You can now enter a number and check whether it is prime. 

For instance, I have checked whether 5 and 1 are prime numbers and got the following;

Primechecker example

How to Upload the Package Online

You can host the package you have created on PyPI (Python Package Index). This a central repository that carries thousands of Python packages. Head to https://pypi.org/ and create an account if you don’t have one.

You can follow these steps now to upload your package online;

  • Step 1: Create a new file in the root folder (mine is primechecker) and name it setup.py.
  • Step 2: Change the contents of the setup.py file to contain information about the package you want to upload.

The code for this file should be as follows;

from setuptools import setup, find_packages

setup(

    name='primechecker',

    version='1.0.0',

    author='Your Name',

    author_email='your@email.com',

    description='A package for checking prime numbers',

    packages=find_packages(),

)

Change the name, author, author_email, and description to suit your package details. 

  • Step 3: Build your package. Run this command while still inside the root folder;
python3 setup.py sdist bdist_wheel

If you check your project folder, you can see two new folders (build and dist) within the root folder. 

  • Step 4: Install twine. This is the package needed to upload packages to PyPI. 

Use this command;

pip install twine
  • Step 5: Upload the package

Use this command;

twine upload dist/*

You will be prompted to input your username and password. If the name of your package is not already taken, the package will be published online, and you will get a link on your terminal.

Primechecker

The package you have just published will be available to the public. Anyone who wishes to use the package can download it using pip. 

For instance, the package I have published can be downloaded as;

pip install primechecker==1.0.0.
Published-Primechecker

Best Practices for Creating Python Packages

  • Pay attention to Python Packaging Standards: Even though you are free to decide on the type of package to create, always remember that Python packages have standards you should adhere to. Check these standards on https://packaging.python.org/ before you start writing your code.
  • Test your package before deploying: Bugs are common in programming. Create scripts for generating automated tests, especially when building large packages. Such an approach ensures that you upload packages that are bug-free. 
  • Versioning: A proper package should follow semantic versioning. The package that I created in our demonstration had these numbers 1.0.0. The first bit (1) is the Major version, the second bit (0) is the Minor version, and the last bit is Patch. 
  • Specify all the dependencies: Depending on your needs, you may have various dependencies or other packages inside your package. You should mention all the dependencies in the description of your package during upload. You can use tools like setuptools or poetry to add and manage these dependencies. 
  • Use version control: Programming is a continuous process. You may keep upgrading or improving your package to add new features or make it more efficient. You may also want to invite contributors. You can upload your package code to platforms like GitHub or GitLab to make your code accessible and allow collaboration. 
  • Document your code: The package we created was for demonstration purposes. However, if you intend to share such a package with the public or team members, you must generate documentation that guides the users. You can use tools like Pydoc or Sphinx to generate your docs. 

Where else can I Upload Python Packages? 

Even though Python Package Index (PyPI) is the official repository for Python packages, it does not mean you are restricted from using it. Some factors to consider when determining where to upload your Python package are the files’ size, the package’s nature, the level of support needed, and your target audience. 

These are other areas where you can upload your Python packages;

  • GitHub: GitHub is the biggest code hosting platform. You can create a repository and add your Python package as a zip file for redistribution. 
  • Conda: Conda is a package manager you can use for your Python packages. This platform is famous among data scientists. Create an account on Conda and start uploading your packages for redistribution. 
  • PyPI Mirrors: There are many PyPI Mirrors that mirror the contents of the PyPI platform. Select one that suits your needs to host your package. 

Conclusion 

You now have the steps of creating Python packages and publishing them online. Our example was just basic, but you can play around and create complex packages. However, always create the right folder structure when building Python packages. 

This article was reviewed by Narendra Mohan Mittal
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder