"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Step by Step: Creating Your First Python Library with Poetry (Part I)

Step by Step: Creating Your First Python Library with Poetry (Part I)

Published on 2024-07-30
Browse:481

Passo a Passo: Criando Sua Primeira Biblioteca em Python com Poetry (Parte I)

Learn how to create your first Python library! In this series of posts, we'll guide you through the process of creating and publishing a Python library using Poetry. Let's start with building a small calculator application, covering everything from initial configuration to implementation and testing of basic functions. At the end of this series, you will have your library ready to share with the world on PyPI.

What is Poetry?

Poetry is a dependency management and packaging tool for Python projects. It simplifies the process of creating and maintaining libraries and applications by automating many tasks that traditionally require multiple tools. Poetry comes with all the tools you might need to manage your projects deterministically. Here are some of the main advantages of Poetry:

  • Build Projects: Build and package your projects easily with a single command.
  • Share your work: Make your work known by publishing it on PyPI.
  • Check the status of your dependencies: Get a view of your project's dependencies with just one command.
  • Dependency Resolution: Poetry comes with an exhaustive dependency resolver, which will always find a solution if one exists.
  • Isolation: Poetry uses configured virtual environments or creates its own to always be isolated from your system.
  • Intuitive CLI: Poetry commands are intuitive and easy to use, default-sensitive yet configurable.

With these advantages, Poetry stands out as a powerful and efficient tool for developing Python projects.

What do we need before starting our Python library?

Before we start writing code, we need to set up our development environment. Here are the steps to ensure you have everything ready:

Check Python version

First, we need to make sure you have the latest version of Python installed. To check the version of Python installed on your system, run the following command in the terminal:

python --version

If you don't already have Python installed or need to update it, you can download and install it from the official Python website.

Installing Poetry

After ensuring you have the latest version of Python installed, the next step is to install Poetry. You can install Poetry by following the instructions detailed in the official documentation. Here is a quick command for installation:

curl -sSL https://install.python-poetry.org | python3 -

Starting Your Library: The First Steps

Step 1: Creating the project with Poetry

Now that we have Python and Poetry installed, it's time to start our calculator project. Poetry makes it easy to create a new project with a simple command.

Navigate to the directory where you want to create your project and run the following command in the terminal:

poetry new calculator
cd calculator

This command creates a new project structure for you, which includes essential folders and files.

calculator/
├── README.md
├── calculator
│   └── __init__.py
├── pyproject.toml
└── tests
    └── __init__.py

Let's understand the generated structure:

  • README.md: A documentation file to describe your project.
  • calculator/: A folder that contains the source code of your application.
  • tests/: A folder for your unit tests.
  • pyproject.toml: The main configuration file for Poetry.

Step 2: Implementing the calculator functions

Now let's create the calculator functions within the calculator/calculator.py file.

calculator/
├── calculator.py
├── __init__.py

Open the calculator.py file and implement the basic calculator functions:

def add(a, b):
    return a   b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Não é possível dividir por zero")
    return a / b

Step 3: Testing the calculator functions

Testing is essential to guarantee software quality, providing reliability in bug fixes and code evolution. In this example, we will use unit tests to validate our calculator functions. Let's set up the testing environment and write some test cases to ensure that the mathematical operations work correctly.

Configuring the testing environment

Start adding pytest as a development dependency:

poetry add --dev pytest

Now, create a file called test_calculator.py inside the tests folder:

import pytest
from calculator.calculator import add, subtract, multiply, divide

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0
    assert add(-1, -1) == -2

def test_subtract():
    assert subtract(5, 2) == 3
    assert subtract(0, 0) == 0
    assert subtract(-1, 1) == -2
    assert subtract(-1, -1) == 0

def test_multiply():
    assert multiply(2, 3) == 6
    assert multiply(5, 0) == 0
    assert multiply(-1, 1) == -1
    assert multiply(-2, -3) == 6

def test_divide():
    assert divide(6, 2) == 3
    assert divide(5, 2) == 2.5
    assert divide(-10, 2) == -5
    with pytest.raises(ValueError):
        divide(4, 0)

Finally, just run the tests with the following command:

poetry run pytest

Step 4: Publishing to GitHub

Now that our application is covered with tests, let's prepare it to be shared on GitHub. Follow the steps below to add your project to GitHub:

  1. Create a repository on GitHub: Go to GitHub and create a new repository for your calculator.

  2. Add your project to the repository:

  • Initialize the Git repository inside your project directory if it is not already initialized:
git init
  • Add all files to Git and make the first commit:
git add .
git commit -m "Initial commit"
  • Connect your local repository to the remote repository on GitHub:
git remote add origin 
  • Upload your files to GitHub:
git push -u origin main

Now your project is on GitHub and ready to be shared and collaborated on with other developers.

Step 5: Installing via Pip or Poetry

To install your library directly, just use the following commands:

  • Via Pip:
pip install git https://github.com/seu_usuario/seu_repositorio.git
  • Via Poetry:
poetry add git https://github.com/seu_usuario/seu_repositorio.git

What comes next?

In this first part of the tutorial, we cover the essential fundamentals for creating a Python library using Poetry. We started by setting up the development environment, implemented a basic calculator with unit tests using pytest, and shared the project on GitHub for collaboration.

In the next part of this tutorial, we'll explore how to publish your library to PyPI, the standard Python package repository, and learn how to install it using Poetry or pip directly from PyPI. This will not only make your library easier for other developers to use, but it will also help integrate you with the Python community.

Congratulations on getting this far! I hope you are enjoying creating your Python library. Feel free to share questions or suggestions in the comments. Let's now move on to Part II and continue our journey of collaboration with the Python community.

References

  • Canal Eduardo Mendes (@Dunossauro) Creating a python package from scratch: from requirements to deployment
  • Poetry Documentation
  • Poetry: building Python packages the easy way
Release Statement This article is reproduced at: https://dev.to/domdias/passo-a-passo-criando-sua-primeira-biblioteca-em-python-com-poetry-parte-i-2alj?1 If there is any infringement, please contact study_golang @163.comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3