How To Create Library and publish on PyPI python
In the world of Python programming, creating reusable and well-organized code is crucial for efficient development. Python libraries play a pivotal role in achieving this goal, as they allow developers to package and distribute their code in a way that can be easily shared and utilized by others. In this article, we’ll explore how to build a Python library using Poetry, a user-friendly dependency management and packaging tool. Whether you’re new to programming or just starting with Python, this guide will help you get started on the path to creating your own Python library.
What is a Python Library?
A Python library is a collection of functions, classes, and modules that are written to perform specific tasks. Libraries are designed to be reusable, meaning they can be easily imported into other projects, saving developers time and effort by eliminating the need to reinvent the wheel for common tasks.
Getting Started with Poetry
Poetry is a modern Python dependency management and packaging tool that simplifies the process of creating and managing Python projects, including libraries.
Install on Linux, MacOS, WSL (Windows)
curl -sSL https://install.python-poetry.org | python3 -
Install on PowerShell (Windows)
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -
after installing, you can check poetry version
poetry --version
Setting Up Your Library Project
Open your terminal and navigate to the directory where you want to create your library. Use the following command to initiate a new Poetry project:
poetry new custom-log
after execute above command, poetry will create folder with structure like this:
.
├── README.md
├── custom_log
│ └── __init__.py
├── pyproject.toml
└── tests
└── __init__.py
open your project directory and create your poetry virtual environment,
cd custom-log
poetry shell
nasri@aliendev:~/Research/custom-log$ poetry shell
Creating virtualenv custom-log-vdAXMe7h-py3.10 in /home/nasri/.cache/pypoetry/virtualenvs
Spawning shell within /home/nasri/.cache/pypoetry/virtualenvs/custom-log-vdAXMe7h-py3.10
Defining Dependencies
Navigate into your newly created project directory using cd custom-log
and open the pyproject.toml
file. This is where you'll define your project's dependencies. Add your required dependencies:
[tool.poetry.dependencies]
python = "^3.10"
loguru = "^0.7.0"
poetry install
or use command:
poetry add loguru
Structuring Your Library
Create a directory structure for your library. You can place your library code inside a subdirectory, such as custom-log
, and add an empty __init__.py
file to make it a package.
Writing Your Library Code
create main.py
file and add example code like this:
# main.py file
import functools
from loguru import logger
def custom_log(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger.info(f"Calling {func.__name__} with arguments {args} and kwargs {kwargs}")
result = func(*args, **kwargs)
logger.info(f"{func.__name__} returned {result}")
return result
return wrapper
create simplify user to access function, open your __init__.py
and add this syntax
from custom_log.main import custom_log
Packaging Your Library
Poetry simplifies packaging by automatically generating a pyproject.toml
file for your project. To create a distributable package, run the following command:
poetry build
This will generate a dist
directory containing your packaged library.
Publishing Your Library
Before publishing your library, make sure you have an account on the Python Package Index (PyPI). You can create one at https://pypi.org/account/register/. Once you have an account,
create API Token on https://pypi.org/manage/account/token/ and select all project for scope
add token on yout device use this command:
poetry config pypi-token.pypi <your token>
you can publish your library using the following command:
poetry publish --build
Conclusion
Poetry, as introduced in this guide, emerged as a user-friendly ally, streamlining the complexities of Python project development. The article’s step-by-step approach, accompanied by clear examples, provided a solid foundation for creating efficient and shareable Python libraries.
By delving into the intricacies of setting up a library project, defining dependencies, and structuring code, the guide empowered readers to embark on their own library-building journeys. The practical demonstration of creating a custom logging function using the loguru library illustrated real-world application, enhancing the learning experience.
Crucially, the article didn’t stop at code creation; it extended its guidance to packaging and publishing on the Python Package Index (PyPI). This final step underscores the article’s commitment to not only fostering coding proficiency but also encouraging the sharing of valuable resources with the wider Python community.
In essence, this guide equips readers with the knowledge and tools needed to contribute to the collaborative spirit of Python programming. Whether one is just starting or seeking to enhance their development practices, the journey from initiation to publication outlined here ensures that building and sharing Python libraries becomes an accessible and rewarding endeavor.