close
close

first Drop

Com TW NOw News 2024

Pip Install YOU: A Beginner’s Guide to Building Your Python Library
news

Pip Install YOU: A Beginner’s Guide to Building Your Python Library

Pip Install YOU: A Beginner’s Guide to Building Your Python Library
Image by Author | Canva

As programmers, we often rely on various external libraries to solve various problems. These libraries are created by skilled developers and provide solutions that save us time and effort. But have you ever thought about it, “Can I also create my own libraries?” The answer is yes! This article will explain the steps needed to help you achieve that, whether you’re 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 creating a library

Step 1: Initialize your project

Start by creating a main folder for your project.

Step 2: Create a directory for your package

The next step is to create a folder for your package within your project folder.

multiples_library/
└──multiples/

Step 3: Add __init.py__

Now add the __init.py__ in your package directory. This file is the primary indicator to Python that the directory it is in is a package. It consists of initialization code, if any, and is executed automatically when a package or one of its modules is 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 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 named setup.py to your package folder.

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 and other files (optional)

This step is not necessary, but it is a good practice if you want to build a flawless and professional library. In this step the project structure is finalized 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 main folder:

  • test/: Contains test cases for your library to ensure 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: Records changes to the library.
  • README.md: Contains a description of your package and installation instructions.
  • requirements.txt: Lists the external dependencies your library requires. 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 directories in no time. However, I want to discuss the optional tests directory a bit to clarify its usage.

testing/ directory

It is important to note that you can add a tests directory within your root directory, i.e. \multiples_libraryor within your package directory, i.e. \multiplesThe choice is yours; however, I prefer to keep it at the top level in the root directory as I think this is a better way to modularize your code.

Several libraries help you write test cases. I will use the most famous and my personal favorite: “unittest.”

Unit Test/s for is_multiple_of_two

The test case(s) for this module are included in 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 are included in 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 above unit tests are pretty simple, but I’ll explain two functions for clarification.

  • self.assertTrue(expression) checks whether the expression evaluates to “True”. The test passes only if the result of the expression is “True”.
  • unittest.main() The function is called to execute all 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 it a token name and selecting the scope for “Entire Account”. Then copy it carefully as it will only appear once.
  • Now you need to create a .pypirc file.
    For MacOS/Linuxopen the terminal and run the following command:
  • For Windowsopen the command prompt and run the following command:

    cd %USERPROFILE%
    type NUL > .pypirc

    The file is created and located in ~/.pypirc in case of MacOS/Linux and %USERPROFILE%/.pypirc in case of Windows.

  • Editing .pypirc file by copying and pasting the following configuration:
  • (distutils)
    index-servers =
        pypi
    
    (pypi)
    username = __token__
    password = pypi-

    Replace with the actual API token you generated from PyPI. Don’t forget to add the pypi- prefix.

  • Make sure you have a setup.py file in the root directory of your project. Run the following command to create distribution files:
  • python3 setup.py sdist bdist_wheel
    
  • 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:

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

Complete

In short, creating a Python library is very interesting and spreading it makes it useful for others. I tried to cover everything you need to create a library in Python as clearly as possible. However, if you get stuck or confused somewhere, don’t hesitate to ask questions in the comments.

Kanwal Mehreen Kanwal is a machine learning engineer and technical writer with a passion for data science and the intersection of AI and medicine. She is the co-author of the e-book “Maximizing Productivity with ChatGPT”. As a Google Generation Scholar 2022 for APAC, she is an advocate for diversity and academic excellence. She has also been recognized as a Teradata Diversity in Tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is a passionate advocate for change and founded FEMCodes to empower women in STEM fields.