Creating a Custom Python Library: Step-by-Step Guide
Step 1: Organize Your Code Into a Directory
First, you need to organize your code. Let’s say you have some code for mathematical operations that you want to turn into a library. Start by creating a new directory for your library:
mkdir my_math_lib
Then, move into this new directory:
cd my_math_lib
Step 2: Create Python Files with Functions/Classes
Inside this directory, create a new Python file for each module in your library. For example, create a `math_operations.py` file:
# math_operations.py def add(a, b): return a + b def subtract(a, b): return a - b
Step 3: Create an __init__.py File
Create a new file named `__init__.py` in the same directory. This file can be empty, but it needs to be present in the directory for Python to recognize the directory as a package.
Step 4: Use the Library Locally
You can now use this library in other Python scripts in the same directory as follows:
# main.py from my_math_lib import math_operations print(math_operations.add(5, 3)) # Output: 8 print(math_operations.subtract(5, 3)) # Output: 2
Step 5: Package the Library for Distribution
If you want to distribute your library to others, you’ll need to package it properly. This typically involves creating a `setup.py` file in the root directory (the same level as the `my_math_lib` folder).
Here’s an example `setup.py`:
# setup.py from setuptools import setup, find_packages setup( name="my_math_lib", version="0.1", packages=find_packages(), )
You can then build and install your library using the following command:
python setup.py install
This will install the library in your current Python environment. You can then import and use the library from anywhere in your system, not just from scripts in the same directory.
Note
Creating a library can get quite complex when you start to deal with dependencies, different Python versions, tests, and other advanced features. This guide is just a basic introduction to the concept. For more complex libraries, you might want to consider using a tool like `poetry` or `conda` to manage your library.