Pip Install YOU: A Beginner's Guide to Creating Your Python Library - KDnuggets (2024)

Pip Install YOU: A Beginner's Guide to Creating Your Python Library - KDnuggets (1)
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.

multiples_library/

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_packagessetup( 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 unittestimport sysimport ossys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from multiples.is_multiple_of_two import is_multiple_of_twoclass 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 unittestimport sysimport ossys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from multiples.is_multiple_of_five import is_multiple_of_fiveclass 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:
  • cd ~touch .pypirc

    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.

  • Edit .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. Do not forget to include the pypi- prefix.

  • Ensure you have a setup.py file in your project’s root directory. Run the following command to create distribution files:
  • python3 setup.py sdist bdist_wheel
  • Twine is a tool that is used to upload packages to PyPI. Install twine by running the following command:
  • pip install twine
  • Now upload your package to PyPI by running the following command:
  • twine upload dist/*

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_fivefrom multiples.is_multiple_of_two import is_multiple_of_twoprint(is_multiple_of_five(10))# Outputs Trueprint(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.


More On This Topic

  • Forget PIP, Conda, and requirements.txt! Use Poetry Instead And…
  • Testing Like a Pro: A Step-by-Step Guide to Python's Mock Library
  • Creating a Web Application to Extract Topics from Audio with Python
  • The Challenges of Creating Features for Machine Learning
  • Winning The Room: Creating and Delivering an Effective Data-Driven…
Pip Install YOU: A Beginner's Guide to Creating Your Python Library - KDnuggets (2024)
Top Articles
How to make Enchilada Sauce
How to Make Plant-Based Vegan Cream Sauce
How To Check Your Rust Inventory Value? 🔫
Trivago Manhattan
Irela Torres Only Fans
Mychart.texaschildrens.org.mychart/Billing/Guest Pay
Fire And Ice Festival Dc
Keanu Reeves cements his place in action genre with ‘John Wick: Chapter 4’
Raymond James Stadium Seat Map Taylor Swift
Buhl Park Summer Concert Series 2023 Schedule
Domino Near
Maryse Mizanin Nip Slip
Her Triplet Alphas Chapter 32
Die 12 besten Chrome Video Downloader im Überblick
Hessaire Mini Split Remote Control Manual
Liquor World Sharon Ma
Greyhound Bus Station Syracuse Ny
ZQuiet Review | My Wife and I Both Tried ZQuiet for Snoring
Sophia Garapetian Twitter
Meridamoonbeams
Rockcastle County Schools Calendar
Liquor Barn Redding
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
E41.Ultipro.com
Ok Google Zillow
Account Now Login In
The Civil Rights Movement Crossword Review Answer Key
Meritas Health Patient Portal
Davis Fire Friday live updates: Community meeting set for 7 p.m. with Lombardo
454 Cubic Inches To Litres
Family Naturist Contest
Texas Motors Specialty Photos
Ticket To Paradise Showtimes Near Laemmle Newhall
Today's Final Jeopardy Clue
Mycourses Wcc
Craigs List New Haven Ct
My.chemeketa
Sdn Md 2023-2024
Dr Ommert Norwalk Ohio
About Baptist Health - Baptist Health
Ces 2023 Badge Pickup
Oriley Auto Parts Hours
I Got Hoes Might Just Be You N
CDER - UTENLANDSKE og NORSKE artister
Ev Gallery
Ucla Football 247
Alle Eurovision Song Contest Videos
Salon5 – Europa, was geht? – Podcast
David Knowles, journalist who helped make the Telegraph podcast Ukraine: The Latest a runaway success
Departments - Harris Teeter LLC
Closest Asian Supermarket
Bme Flowchart Psu
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 5791

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.