コンテンツにスキップ

Poetry Cheatsheet

Poetry Cheatsheet

Installation

PlatformCommand
Linux/macOS (Official)`curl -sSL https://install.python-poetry.org \
macOS (Homebrew)brew install poetry
Windows (PowerShell)`(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content \
Any Platform (pipx)pipx install poetry
Verify Installationpoetry --version
Update Poetrypoetry self update
Update to Specific Versionpoetry self update 1.5.0
Add to PATH (if using official installer):
export PATH="$HOME/.local/bin:$PATH"
# Add to ~/.bashrc or ~/.zshrc for persistence

Basic Commands

CommandDescription
poetry new my-projectCreate new project with standard structure
poetry new my-project --srcCreate project with src layout
poetry initInitialize Poetry in existing project (interactive)
poetry installInstall all dependencies from lock file
poetry add requestsAdd package to dependencies
poetry add pytest --group devAdd package to dev dependencies
poetry remove requestsRemove package from dependencies
poetry updateUpdate all dependencies to latest allowed versions
poetry update requestsUpdate specific package
poetry showList all installed packages
poetry show --treeShow dependency tree
poetry show requestsShow details of specific package
poetry lockGenerate/update poetry.lock file
poetry checkValidate pyproject.toml and poetry.lock
poetry run python script.pyRun command in virtual environment
poetry run pytestRun tests in virtual environment
poetry shellActivate virtual environment
poetry env infoShow virtual environment information
poetry env listList all virtual environments
poetry buildBuild source and wheel distributions

Advanced Usage

CommandDescription
poetry add requests@^2.28.0Add package with caret version constraint (>=2.28.0 <3.0.0)
poetry add requests@~2.28.0Add package with tilde constraint (>=2.28.0 <2.29.0)
poetry add "requests>=2.28,<3.0"Add package with complex version range
poetry add git+https://github.com/user/repo.gitAdd package from Git repository
poetry add ./path/to/package --editableAdd local package in editable mode
poetry install --without dev,testInstall dependencies excluding specific groups
poetry install --with docsInstall dependencies including optional group
poetry install --only mainInstall only main dependencies
poetry install --syncSync environment with lock file (remove extras)
poetry update --dry-runPreview dependency updates without applying
poetry show --outdatedShow packages with available updates
poetry show --latestShow latest available versions
poetry env use python3.11Use specific Python version for environment
poetry env use /usr/bin/python3.9Use specific Python interpreter path
poetry env remove python3.11Remove specific virtual environment
poetry export -f requirements.txt -o requirements.txtExport dependencies to requirements.txt
poetry export --without-hashes -o requirements.txtExport without hash verification
poetry publishPublish package to PyPI
poetry publish --buildBuild and publish in one command
poetry publish --dry-runTest publish without uploading
poetry config --listList all configuration settings
poetry config virtualenvs.in-project trueCreate .venv in project directory
poetry source add private https://pypi.example.com/simple/Add custom package source
poetry cache clear pypi --allClear Poetry cache

Configuration

Primary Configuration File: pyproject.toml

[tool.poetry]
name = "my-project"
version = "0.1.0"
description = "Project description"
authors = ["Your Name <you@example.com>"]
readme = "README.md"
license = "MIT"
homepage = "https://example.com"
repository = "https://github.com/user/repo"
keywords = ["keyword1", "keyword2"]
classifiers = [
    "Development Status :: 4 - Beta",
    "Programming Language :: Python :: 3.11",
]
packages = [{include = "my_package"}]

[tool.poetry.dependencies]
python = "^3.11"
requests = "^2.28.0"
pydantic = {version = "^2.0", optional = true}

[tool.poetry.group.dev.dependencies]
pytest = "^7.0"
black = "^23.0"
mypy = "^1.0"

[tool.poetry.group.docs.dependencies]
sphinx = "^5.0"

[tool.poetry.extras]
data = ["pydantic"]

[tool.poetry.scripts]
my-cli = "my_package.cli:main"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

Global Configuration Settings

SettingCommandDescription
Create venv in projectpoetry config virtualenvs.in-project trueCreate .venv folder in project root
Set venv pathpoetry config virtualenvs.path "/path/to/venvs"Custom location for virtual environments
Parallel installationpoetry config installer.parallel trueEnable parallel package installation
Max workerspoetry config installer.max-workers 10Set maximum parallel workers
Cache directorypoetry config cache-dir "/path/to/cache"Set custom cache location
PyPI tokenpoetry config pypi-token.pypi your-tokenSet PyPI authentication token
View settingpoetry config virtualenvs.in-projectDisplay specific configuration value
Unset settingpoetry config virtualenvs.in-project --unsetRemove configuration setting
Local configpoetry config --local virtualenvs.in-project trueSet project-specific configuration

Version Constraint Operators

OperatorExampleMeaning
Caret ^^2.28.0>=2.28.0 <3.0.0 (compatible versions)
Tilde ~~2.28.0>=2.28.0 <2.29.0 (patch updates)
Exact2.28.0Exactly version 2.28.0
Greater/Equal>=2.28.0Version 2.28.0 or higher
Range>=2.28,<3.0Between 2.28 and 3.0
Wildcard2.28.*Any patch version of 2.28
Latest@latestLatest available version

Common Use Cases

Use Case 1: Starting a New Python Project

# Create new project with src layout
poetry new my-app --src

# Navigate to project
cd my-app

# Add production dependencies
poetry add fastapi uvicorn pydantic-settings

# Add development dependencies
poetry add pytest pytest-cov black mypy --group dev

# Install all dependencies
poetry install

# Activate virtual environment
poetry shell

Use Case 2: Converting Existing Project to Poetry

# Navigate to existing project
cd existing-project

# Initialize Poetry (interactive)
poetry init

# Add existing dependencies
poetry add requests flask sqlalchemy

# Add dev dependencies from requirements-dev.txt
poetry add pytest black flake8 --group dev

# Generate lock file
poetry lock

# Install everything
poetry install

Use Case 3: Managing Multiple Dependency Groups

# Install with documentation dependencies
poetry install --with docs

# Install without test dependencies
poetry install --without test

# Install only main dependencies (no dev/test)
poetry install --only main

# Add dependencies to specific groups
poetry add sphinx sphinx-rtd-theme --group docs
poetry add locust --group perf

Use Case 4: Building and Publishing a Package

# Update version in pyproject.toml
poetry version patch  # 0.1.0 -> 0.1.1
poetry version minor  # 0.1.1 -> 0.2.0
poetry version major  # 0.2.0 -> 1.0.0

# Build package
poetry build

# Test publish to TestPyPI
poetry config repositories.testpypi https://test.pypi.org/legacy/
poetry publish -r testpypi --username __token__ --password $TEST_PYPI_TOKEN

# Publish to PyPI
poetry publish --username __token__ --password $PYPI_TOKEN

Use Case 5: Working with Private Package Repositories

# Add private repository
poetry source add --priority=supplemental private-repo https://pypi.company.com/simple/

# Configure authentication
poetry config http-basic.private-repo username password

# Or use token authentication
poetry config pypi-token.private-repo your-token

# Add package from private repo
poetry add internal-package

# Publish to private repo
poetry publish -r private-repo

Use Case 6: CI/CD Integration

# Install Poetry in CI
curl -sSL https://install.python-poetry.org | python3 -

# Install dependencies (no dev dependencies)
poetry install --without dev --no-interaction --no-ansi

# Export for Docker or other tools
poetry export -f requirements.txt --output requirements.txt --without-hashes

# Run tests
poetry run pytest

# Build package
poetry build

Best Practices

  • Commit poetry.lock: Always commit the lock file to version control to ensure reproducible builds across all environments and team members.

  • Use dependency groups: Organize dependencies into logical groups (dev, test, docs) instead of the deprecated --dev flag for better control and flexibility.

  • Pin Python version: Specify the Python version constraint in pyproject.toml to prevent compatibility issues across different environments.

  • Use poetry.lock for applications: For applications and services, rely on the lock file for exact versions. For libraries, test against the range of versions specified in pyproject.toml.

  • Prefer poetry install --sync: In CI/CD pipelines, use --sync to ensure the environment exactly matches the lock file, removing any extraneous packages.

  • Set virtualenvs.in-project: Configure Poetry to create virtual environments in the project directory (poetry config virtualenvs.in-project true) for easier IDE integration and cleanup.

  • Use version constraints wisely: Use caret (^) for most dependencies to allow compatible updates, but use exact versions for packages with unstable APIs or breaking changes.

  • Export for compatibility: Generate requirements.txt files when needed for tools that don’t support Poetry, especially in Docker containers or legacy systems.

  • Keep Poetry updated: Regularly update Poetry itself (poetry self update) to benefit from bug fixes, performance improvements, and new features.

  • Use poetry check before commits: Validate your pyproject.toml and poetry.lock files before committing to catch configuration errors early.

Troubleshooting

IssueSolution
poetry: command not foundAdd Poetry to PATH: export PATH="$HOME/.local/bin:$PATH" or restart terminal after installation
Virtual environment not activatingUse poetry shell or run commands with poetry run. Check poetry env info to verify environment exists
Dependency resolution takes too longClear cache with poetry cache clear pypi --all, update Poetry, or try poetry lock --no-update
Lock file out of sync errorsRun poetry lock --no-update to regenerate lock file, or poetry install --sync to match environment to lock
Package not found in private repoVerify source configuration with poetry source show, check authentication with poetry config --list
SolverProblemError during installCheck for conflicting version constraints in pyproject.toml, try updating dependencies with poetry update
Poetry using wrong Python versionSpecify Python explicitly: poetry env use python3.11 or poetry env use /path/to/python
Cannot publish to PyPI (authentication)Configure token: poetry config pypi-token.pypi your-token or use --username and --password flags
poetry.lock merge conflictsRun poetry lock --no-update after resolving conflicts in pyproject.toml to regenerate lock file
Slow package installationEnable parallel installation: poetry config installer.parallel true and adjust workers if needed
IDE not detecting virtual environmentUse poetry config virtualenvs.in-project true and point IDE to .venv directory in project root