Home > Article > Backend Development > Step by Step: Creating Your First Python Library with Poetry (Part 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.
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:
With these advantages, Poetry stands out as a powerful and efficient tool for developing Python projects.
Before we start writing code, we need to set up our development environment. Here are the steps to ensure you have everything ready:
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.
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 -
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:
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
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.
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
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:
Crie um repositório no GitHub: Vá para o GitHub e crie um novo repositório para sua calculadora.
Adicione seu projeto ao repositório:
git init
git add . git commit -m "Initial commit"
git remote add origin <URL_DO_SEU_REPOSITORIO_GITHUB>
git push -u origin main
Agora seu projeto está no GitHub e pronto para ser compartilhado e colaborado com outros desenvolvedores.
Para instalar sua biblioteca diretamente basta usar os seguintes comandos:
pip install git+https://github.com/seu_usuario/seu_repositorio.git
poetry add git+https://github.com/seu_usuario/seu_repositorio.git
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.
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!