Image by Author | Canva
As programmers, we often rely on various external libraries to solve different problems. These libraries are created by skillful 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 necessary steps to help you accomplish that, whether you are a professional developer or just starting out. From writing and structuring your code to documentation and publishing, this guide covers it all.
Step-by-Step Guide to Create 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 within your project’s directory.
multiples_library/
└──multiples/
Step 3: Add __init.py__
Now, add the __init.py__
within your package’s directory. This file is the primary indicator to Python that the directory it resides in is a package. It consists of initialization code if any and executes automatically 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’s directory. These modules typically consist of classes and functions. It is a good practice to give each module a meaningful name describing its purpose.
multiples_library/
│
└── multiples/
├── __init__.py
├── is_multiple_of_two.py
└── is_multiple_of_five.py
Step 5: Write into the Modules
In this step, you’ll 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’s directory.
multiples_library/
│
├── multiples/
│ ├── __init__.py
│ ├── is_multiple_of_two.py
│ └── is_multiple_of_five.py
│
└──setup.py
This file contains metadata about your 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 & Other Files [Optional]
This step is not necessary, but it is a good practice if you want to build an error-free and professional library. At this step, the project structure is final and looks somewhat 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 optional files and folders which are mentioned in the root directory:
- tests/: Contains test cases for your library to ensure it behaves as expected.
- docs/: Contains documentation for your library.
- LICENSE.txt: Contains the licensing terms under which others can use your code.
- CHANGES.txt: Records changes to the library.
- README.md: Contains the description of your package, 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 will get the purpose of the optional files and folders in no time. However, I would like to discuss the optional tests directory a little to clarify its usage.
tests/ directory
It is important to note that you can add a tests directory within your root directory, i.e., \multiples_library
, or within your package’s directory, i.e., \multiples
. The choice is yours; however, I like to keep it at the top level within the root directory as I think it is a better way to modularize your code.
Several libraries help you write test cases. I will use the most famous one and my personal favorite “unittest.”
Unit Test/s for is_multiple_of_two
The test case/s for this module is included inside the test_is_multiple_of_two.py
file.
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 Test/s for is_multiple_of_five
The test case/s for this module is included inside the test_is_multiple_of_five.py
file.
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 will explain two functions for further clarification.
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()
function is called to run 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 an API token by giving a token name and selecting scope to the “Entire account.” Then, copy it carefully as it only appears once.
- Now, you need to create a .pypirc file.
For MacOS/Linux, open the terminal and run the following command: - Edit .pypirc file by copying and pasting the following configuration:
- Ensure you have a setup.py file in your project’s root directory. Run the following command to create distribution files:
- Twine is a tool that is 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 Windows, open the command prompt and run the following command:
cd %USERPROFILE%
type NUL > .pypirc
The file is created and resides at ~/.pypirc in the case of MacOS/Linux and %USERPROFILE%/.pypirc in the case of Windows.
[distutils]
index-servers =
pypi
[pypi]
username = __token__
password = pypi-
Replace
python3 setup.py sdist bdist_wheel
Step 9: Install and Use the Library
You can install the library by the following command:
pip install [your-package]
In my case:
pip install multiples_library
Now, you can 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
Wrapping Up
In short, creating a Python library is very interesting, and distributing it makes it useful for others. I have tried to cover everything you need to create a library in Python as clearly as possible. However, if you get stuck or confused at any point, please don’t hesitate to ask questions in the comments section.
Kanwal Mehreen Kanwal is a machine learning engineer and a technical writer with a profound passion for data science and the intersection of AI with medicine. She co-authored the ebook “Maximizing Productivity with ChatGPT”. As a Google Generation Scholar 2022 for APAC, she champions diversity and academic excellence. She’s also recognized as a Teradata Diversity in Tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having founded FEMCodes to empower women in STEM fields.