-
I created this repository to learn how to create a Python package and publish it to PyPI.
-
This repository uses
poetryto manage dependencies and packaging.
These are the steps to get ready to use poetry.
⛔️ Poetry should always be installed in a dedicated virtual environment to isolate it from the rest of your system. In no case, it should be installed in the environment of the project that is to be managed by Poetry. This ensures that Poetry’s own dependencies will not be accidentally upgraded or uninstalled. (See reference).
Because of the above:
First we create a virtual environment:
python -m venv venvThen we activate it:
source venv/bin/activateFirst check if you have pipx installed. If not, install it with pip:
pip install --user pipxThen install poetry with pipx:
pipx install poetryIf you want to use poetry as a command, you can add an alias to your .bashrc (or .zshrc).
This is what it looks like on my machine:
alias poetry='/Users/abdullahguser/Library/Application\ Support/pipx/venvs/poetry/bin/poetry'I assume you already have a project that you want to manage with poetry. First cd into the project directory.
poetry initThis will create a pyproject.toml file in your project directory.
poetry add <dependency>This will add the dependency to your pyproject.toml file and install it in your virtual environment.
poetry remove <dependency>poetry installThis will install all the dependencies listed in your pyproject.toml file and create a poetry.lock file. (You can commit this file to your repository to ensure that all developers use the same versions of the dependencies.)
cat requirements.txt | xargs poetry addIf you clone a project that uses poetry for dependency management, you can create a virtual environment for it using poetry.
First, if you want this environment to be created under the project directory, set this config:
poetry config virtualenvs.in-project trueNow you can create a virtual environment for the project:
poetry installThis will create a virtual environment for the project and install all the dependencies listed in the pyproject.toml file.
If you want to use this new virtual environment, activate it:
poetry shellTo get out of the virtual environment, type exit or deactivate.
First indicate where you want to publish your package:
poetry config repositories.test-pypi https://test.pypi.org/legacy/Now you can go to this repository and get a token that allows you to publish packages to the repository. Set it in poetry:
poetry config pypi-token.test-pypi <token>Now you can build your package:
poetry buildTo publish your package:
poetry publish -r test-pypiList virtual environments:
poetry env listTo remove a virtual environment, you can simply delete the directory that contains it.
- How to Create and Use Virtual Environments in Python With Poetry
- What is the advantage of using
poetryoverrequirements.txt?
- How to use test pypi? See python-preview.yml.