Home  >  Article  >  Backend Development  >  Step by Step: Creating Your First Python Library with Poetry (Part I)

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

王林
王林Original
2024-07-20 01:19:20948browse

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 it 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, with sensible defaults, 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 by 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)

Por fim, basta executar os testes com o seguinte comando:

poetry run pytest

Passo 4: Publicando no GitHub

Agora que nossa aplicação já está coberta com testes, vamos prepará-la para ser compartilhada no GitHub. Siga os passos abaixo para adicionar seu projeto ao GitHub:

  1. Crie um repositório no GitHub: Vá para o GitHub e crie um novo repositório para sua calculadora.

  2. Adicione seu projeto ao repositório:

  • Inicialize o repositório Git dentro do diretório do seu projeto se ainda não estiver inicializado:
git init
  • Adicione todos os arquivos ao Git e faça o primeiro commit:
git add .
git commit -m "Initial commit"
  • Conecte seu repositório local ao repositório remoto no GitHub:
git remote add origin <URL_DO_SEU_REPOSITORIO_GITHUB>
  • Envie seus arquivos para o GitHub:
git push -u origin main

Agora seu projeto está no GitHub e pronto para ser compartilhado e colaborado com outros desenvolvedores.

Passo 5: Instalando via Pip ou Poetry

Para instalar sua biblioteca diretamente basta usar os seguintes comandos:

  • 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

O que vem a seguir?

Nesta primeira parte do tutorial, cobrimos os fundamentos essenciais para criar uma biblioteca Python utilizando o Poetry. Começamos configurando o ambiente de desenvolvimento, implementamos uma calculadora básica com testes unitários usando pytest, e compartilhamos o projeto no GitHub para colaboração.

Na próxima parte deste tutorial, exploraremos como publicar sua biblioteca no PyPI, o repositório padrão de pacotes Python, e aprenderemos como instalá-la usando o Poetry ou pip diretamente do PyPI. Isso não apenas facilitará o uso da sua biblioteca por outros desenvolvedores, mas também ajudará a integrá-la com a comunidade Python.

Parabéns por chegar até aqui! Espero que esteja aproveitando a criação da sua biblioteca Python. Fique à vontade para compartilhar dúvidas ou sugestões nos comentários. Vamos agora para a Parte II e continuar nossa jornada de colaboração com a comunidade Python.

Referências

  • Canal Eduardo Mendes (@Dunossauro) Criando um pacote python do zero: dos requisitos ao deploy
  • Documentação Poetry
  • Poetry: construindo pacotes Python de uma forma fácil

The above is the detailed content of Step by Step: Creating Your First Python Library with Poetry (Part I). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn