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

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

Jul 20, 2024 am 01:19 AM

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
Copy after login

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 -
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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

Copy after login

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
Copy after login

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)

Copy after login

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

poetry run pytest
Copy after login

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
Copy after login
  • Adicione todos os arquivos ao Git e faça o primeiro commit:
git add .
git commit -m "Initial commit"
Copy after login
  • Conecte seu repositório local ao repositório remoto no GitHub:
git remote add origin <URL_DO_SEU_REPOSITORIO_GITHUB>
Copy after login
  • Envie seus arquivos para o GitHub:
git push -u origin main
Copy after login

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
Copy after login
  • Via Poetry:
poetry add git+https://github.com/seu_usuario/seu_repositorio.git
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

See all articles