Author's image | Canva
As programmers, we often resort to various external libraries to solve different problems. These libraries are created by expert developers and provide solutions that save us time and effort. But have you ever thought, “Can I create my custom libraries too?” The answer is yes! This article explains the steps needed to help you achieve this, whether you are a professional developer or just starting out. This guide covers everything from writing and structuring code to documenting and publishing.
Step-by-step guide to creating a library
Step 1: Initialize your project
Start by creating a root directory for your project.
Step 2: Create a directory for your package
The next step is to create a directory for your package inside your project directory.
multiples_library/
└──multiples/
Step 3: Add __init.py__
Now, add the __init.py__
inside your package directory. This file is the primary indicator to Python that the directory you are in is a package. It consists of the initialization code, if any, and is automatically executed when a package or any of its modules are imported.
multiples_library/
└── multiples/
└──__init__.py
Step 4: Add Modules
Now, you need to add modules to the package directory. These modules usually consist of classes and functions. It is good practice to give each module a meaningful name that describes its purpose.
multiples_library/
│
└── multiples/
├── __init__.py
├── is_multiple_of_two.py
└── is_multiple_of_five.py
Step 5: Write in the modules
In this step, you will define the functionality of each module. For example, in my case:
Module: multiple_of_two.py
def is_multiple_of_two(number):
""" Check if a number is a multiple of two. """
return number % 2 == 0
Module: multiple_of_five.py
def is_multiple_of_five(number):
""" Check if a number is a multiple of five. """
return number % 5 == 0
Step 6: Add setup.py
The next step is to add another file called setup.py to your package directory.
multiples_library/
│
├── multiples/
│ ├── __init__.py
│ ├── is_multiple_of_two.py
│ └── is_multiple_of_five.py
│
└──setup.py
This file contains metadata about the package, such as its name, dependencies, author, version, description, and more. It also defines which modules to include and provides instructions for building and installing the package.
from setuptools import setup, find_packages
setup(
name="multiples_library", # Replace with your package’s name
version='0.1.0',
packages=find_packages(),
install_requires=(
# List your dependencies here
),
author="Your name",
author_email="Your e-mail",
description='A library for checking multiples of 2 and 5.',
classifiers=(
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License', # License type
'Operating System :: OS Independent',
),
python_requires=">=3.6",
)
Step 7: Add tests and other files (optional)
This step is not necessary, but it is a good practice if you want to create a professional and error-free library. At this step, the project structure is final and looks something like this:
multiples_library/
│
├── multiples/
│ ├── __init__.py
│ ├── is_multiple_of_two.py
│ └── is_multiple_of_five.py
│
│
├── tests/
│ ├── __init__.py
│ ├── test_is_multiple_of_two.py
│ └── test_is_multiple_of_five.py
│
├── docs/
│
├── LICENSE.txt
├── CHANGES.txt
├── README.md
├── setup.py
└── requirements.txt
Now I will explain to you what is the purpose of the optional files and folders mentioned in the root directory:
- evidence/: Contains test cases for your library to ensure that it behaves as expected.
- documents/: Contains documentation for your library.
- LICENSE.txt: Contains the license terms under which others can use your code.
- CHANGES.txt: Record changes to the library.
- README.md: Contains your package description and installation instructions.
- requirements.txt – Lists the external dependencies required by your library and you can install these packages with a single command (
pip install -r requirements.txt
).
These descriptions are pretty straightforward and you'll understand the purpose of the optional files and folders in no time. However, I'd like to discuss the optional test directory a bit to clarify its use.
tests/ directory
It is important to note that you can add a testing directory inside your root directory, i.e. \multiples_library
or inside your package directory, i.e. \multiples
The choice is yours, however I prefer to keep it at the top level within the root directory as I think it is a better way to modularize your code.
There are several libraries that help you write test cases. I will use the most famous and my favorite one: “unittest”.
Unit tests for is_multiple_of_two
The test cases for this module are included within the test_is_multiple_of_two.py
archive.
import unittest
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from multiples.is_multiple_of_two import is_multiple_of_two
class TestIsMultipleOfTwo(unittest.TestCase):
def test_is_multiple_of_two(self):
self.assertTrue(is_multiple_of_two(4))
if __name__ == '__main__':
unittest.main()
Unit tests for is_multiple_of_five
The test cases for this module are included within the test_is_multiple_of_five.py
archive.
import unittest
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from multiples.is_multiple_of_five import is_multiple_of_five
class TestIsMultipleOfFive(unittest.TestCase):
def test_is_multiple_of_five(self):
self.assertTrue(is_multiple_of_five(75))
if __name__ == '__main__':
unittest.main()
The unit tests above are pretty straightforward, but I'll explain two functions for clarity.
self.assertTrue(expression)
Checks whether the expression evaluates to “True”. The test will only pass if the result of the expression is “True”.unittest.main()
The function is called to execute all the test cases defined in the file.
Step 8: Distribute your package using PyPI
To make your library easily accessible to others, you can upload it to PyPI. Follow these steps to distribute your package:
- Create an account on PyPI and enable two-factor authentication.
- Create a API Token by giving a token name and selecting the “Entire Account” scope. Then copy it carefully as it only appears once.
- Now you need to create a .pypirc file.
For Mac/Linux operating systemopen terminal and run the following command: - Edit .pypirc file by copying and pasting the following configuration:
- Make sure you have a setup.py file in the root directory of your project. Run the following command to create distribution files:
- Twine is a tool used to upload packages to PyPI. Install Twine by running the following command:
- Now upload your package to PyPI by running the following command:
For WindowsOpen command prompt and run the following command:
cd %USERPROFILE%
type NUL > .pypirc
The file is created and resides in ~/.pypirc for MacOS/Linux and %USERPROFILE%/.pypirc for Windows.
(distutils)
index-servers =
pypi
(pypi)
username = __token__
password = pypi-
Replace with the actual API token you generated from PyPI. Don't forget to include the pypi- prefix.
python3 setup.py sdist bdist_wheel
Step 9: Install and use the library
You can install the library with the following command:
pip install (your-package)
In my case:
pip install multiples_library
You can now use the library as follows:
from multiples.is_multiple_of_five import is_multiple_of_five
from multiples.is_multiple_of_two import is_multiple_of_two
print(is_multiple_of_five(10))
# Outputs True
print(is_multiple_of_two(11))
# Outputs False
Ending up
In short, creating a Python library is very interesting and distributing it makes it useful to others. I have tried to cover everything needed to create a Python library as clearly as possible. However, if at any point you get stuck or confused, feel free to ask questions in the comments section.
Kanwal Mehreen Kanwal is a machine learning engineer and technical writer with a deep passion for data science and the intersection of ai with medicine. She is the co-author of the eBook “Maximizing Productivity with ChatGPT.” As a Google Generation Scholar 2022 for APAC, she champions diversity and academic excellence. She is also recognized as a Teradata Diversity in tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change and founded FEMCodes to empower women in STEM fields.