Poetry
Overview of the Poetry Dependency Management and Packaging Tool
When it comes to managing virtual environments in Python, poetry can be used as an alternative to pip. I prefer poetry over pip because I think it's easier to handle virtual environments and dependencies in poetry.
I like how poetry allows for the grouping of dependencies in the pyproject.toml, which is something I've always liked about package.json files in node.js projects. One example of this is separating project dependencies from dev dependencies.
Note that the instructions below are for MacOS, but the core Poetry commands are consistent across MacOS, Linux, and Windows. Also, the setup below is based on my personal preference for configuring poetry.
Initial Setup
Go to
~/Applications/Pythonin a new Finder window and clickInstall Certificates.command.Open up a terminal in the root directory
~and run the following curl command to install poetry.
curl -sSL https://install.python-poetry.org | python3 -Go to your bash profile in
~/.bash_profile, add the following line, and save the file.
export PATH="/Users/<INSERT_USER_NAME>/.local/bin:${PATH}"Restart your terminal (or run
source ~/.bash_profile) and runpoetry --versionto make surepoetrywas installed and can be properly mapped.Run
poetry config --listin the terminal to see a list ofpoetrysettings.To optionally store virtual environments in project directories, you can modify the setting:
virtualenvs.in-project. This is set tonullby default, but we can change it totruewith the command below.
poetry config virtualenvs.in-project trueRun
poetry config --listto make sure thevirtualenvs.in-projectsetting was updated fromnulltotrue.
Project Setup
To start new project, run
poetry new <project_name>If adding poetry to an existing project,
cdinto the project’s root directory and run
poetry initTo activate the virtual environment, run
poetry shellWorkflow
Once the project is set up with Poetry, here are the common commands one must do on a regular basis:
Run poetry shell to activate the virtual environment.
Run poetry install to sync your virtual environment with the latest dependencies.
Run poetry run <script_name> to run a script defined in pyproject.toml.
Run poetry add <package_name> to install a package.
Run poetry remove <package_name> to uninstall a package.
Run poetry show or poetry show --tree to see al ist of installed dependencies.
Last updated
Was this helpful?