Background
Currently maintaining two Python packages:
Previously, I used setup.py for packaging. However, when updating NJUlogin in November, I encountered this warning:
Therefore, I decided to switch to the new pyproject.toml approach for packaging. At the time, I briefly learned Poetry and adapted it for NJUlogin. Today, while updating mijia-api, I wanted to make a similar adaptation but realized I had forgotten how. So I'm writing this blog post to document it. It seems I'll be using Poetry more frequently for dependency management going forward.
Poetry
Poetry positions itself as: "Python packaging and dependency management made easy." It works similarly to npm (if you're familiar with Node.js), managing dependencies via command-line interface.
But Poetry is too long—henceforth, you'll be called pop.
Installation
Check the official documentation: https://python-poetry.org/docs/#installation I installed it using pipx.
Initialize an existing project
This generates the following pyproject.toml file:
However, since my package contains uppercase letters, I need to change the name under [tool.poetry] and manually add a packages entry. I also need to include other configurations from setup.py:
Create a Poetry virtual environment and install dependencies
By default, Poetry creates the virtual environment in ~/.cache/pypoetry. You can modify this using pop config; see the documentation here. Personally, I prefer placing it within the project directory:
Then, you can install dependencies from requirements.txt, one by one. The following command writes dependencies into pyproject.toml and generates poetry.lock:
One major advantage of Poetry is its ability to display dependencies in a tree structure:
At this point, you can safely delete the original setup.py.
Build and publish
You can use poetry-dynamic-versioning to dynamically set the version, eliminating the need to manually update pyproject.toml each time.
Now, you can build with a single command:
Unlike twine, which stores PyPI tokens in ~/.pypirc, Poetry requires explicit configuration:
Then, you can publish: