[Avg. reading time: 6 minutes]
Poetry
A Dependency & Environment Manager
Poetry simplifies dependency management and packaging in Python projects.
Create a new project:
poetry new helloworld
Sample layout of the directory structure
helloworld/
├── pyproject.toml
├── README.md
├── helloworld/
│ └── __init__.py
└── tests/
└── __init__.py
- Navigate to your project directory
cd helloworld
Windows Users (Recommended Approach)
Working with Virtual Environments
- Create and activate a virtual environment:
poetry env activate
- Get Virtual Python Interpreter info, to verify the base Python vs Poetry env
poetry env info
Or Use this one line.
poetry env use $(poetry env info -e)
- Verify the Virtual env libraries. You will notice only pip.
poetry run pip list
- Add project dependencies:
poetry add faker
- Create a main.py under src/hellworld/ (subfolder)
main.py
from faker import Faker
fake = Faker()
print(fake.name())
- Run program
poetry run python src/helloworld/main.py
Managing Your Project
- View all installed dependencies:
poetry show
- Update dependencies:
poetry update
- Remove a dependency:
poetry remove package-name
Key Benefits
- Simplified Environment Management
- Poetry automatically creates and manages virtual environments
- No need to manually manage pip and virtualenv
- Clear Dependency Specification
- All dependencies are listed in one file (pyproject.toml)
- Dependencies are automatically resolved to avoid conflicts
- Project Isolation
- Each project has its own dependencies
- Prevents conflicts between different projects
- Easy Distribution
- Package your project with a single command:
poetry build
Publish to PyPI when ready:
poetry publish
Best Practices
- Always activate virtual environment before working on project
- Keep pyproject.toml updated with correct dependencies
- Use version constraints wisely
- Commit both pyproject.toml and poetry.lock files to version control