Back to blog

Quản Lý Package Python với Poetry: Quản Lý Dependency Hiện Đại

pythonpoetrypackage-managementdependenciespyproject
Quản Lý Package Python với Poetry: Quản Lý Dependency Hiện Đại

Poetry là tiêu chuẩn hiện đại cho quản lý dự án Python. Nó handles dependencies, virtual environments, và package publishing với một tool duy nhất, sử dụng chuẩn pyproject.toml. Hướng dẫn này covers từ basic setup đến publishing packages của riêng bạn.

Những Gì Bạn Sẽ Học

✅ Cài đặt và thiết lập Poetry
✅ Tạo dự án mới với Poetry
✅ Quản lý dependencies với pyproject.toml
✅ Quản lý virtual environment
✅ Dependency resolution và lock files
✅ Dev dependencies và extras
✅ Publishing packages lên PyPI
✅ Best practices cho các dự án Python

Điều Kiện Tiên Quyết

Trước khi tìm hiểu Poetry, bạn nên hiểu:


Ghi chú: Phần này chứa các ví dụ code tương tự phiên bản tiếng Anh. Để tiết kiệm không gian, chúng tôi tập trung vào giải thích khái niệm bằng tiếng Việt và giữ nguyên code examples.

1. Tại Sao Poetry Thay Vì pip?

Vấn đề với pip + requirements.txt: Không có version locking, không smart conflict resolution, cần tools riêng cho virtual envs, khó reproduce environment.

Featurepip + requirements.txtPoetry
Lock fileManual (pip freeze)Automatic (poetry.lock)
Version resolutionNoneSmart conflict resolution
Virtual envsSeparate toolBuilt-in
Dev dependenciesSeparate fileSingle pyproject.toml
Publishingsetuptools + twineSingle command
ReproducibilityDifficultGuaranteed

2. Cài Đặt Poetry

Official Installer: curl -sSL https://install.python-poetry.org | python3 -

Verify: poetry --version

Configure: poetry config virtualenvs.in-project true (recommended - tạo venv trong project directory)

3. Tạo Dự Án Mới

New project: poetry new my-project creates complete structure với pyproject.toml, README, package directory, và tests.

Existing directory: poetry init với interactive prompts.

pyproject.toml structure: [tool.poetry] (metadata), [tool.poetry.dependencies] (dependencies), [build-system] (build config).

4. Quản Lý Dependencies

Adding: poetry add requests (production), poetry add --group dev pytest (dev).

Version constraints:

  • ^2.31 (caret): >=2.31.0 <3.0.0
  • ~2.31 (tilde): >=2.31.0 <2.32.0
  • >=2.0,<3.0 (explicit range)

Updating: poetry update (all), poetry update requests (specific).

Removing: poetry remove package.

Viewing: poetry show --tree (dependency tree), poetry show --outdated (outdated packages).

5. Lock File

poetry.lock records exact versions của tất cả installed packages. Ensures reproducibility - Developer A và Developer B get same versions.

Commands: poetry install (install from lock), poetry lock (update lock only), poetry check (verify lock is up to date).

Rule: Commit poetry.lock cho applications, không commit cho libraries.

6. Virtual Environment Management

Automatic: Poetry tự động creates venv khi poetry install.

Managing: poetry shell (activate), poetry run command (run without activating), poetry env info (show info), poetry env list (list all).

Python version: poetry env use python3.11 để switch Python version.

7. Dependency Groups

Organize dependencies: [tool.poetry.group.dev.dependencies], [tool.poetry.group.docs.dependencies], etc.

Working with groups: poetry install --without dev (exclude), poetry install --only main (only main).

8. Optional Dependencies và Extras

Define optional dependencies với optional = true, group into extras với [tool.poetry.extras].

Installing: poetry install --extras "cache tasks".

9. Scripts và Entry Points

Define trong [tool.poetry.scripts]: my-cli = "my_project.cli:main".

After poetry install, scripts available: poetry run my-cli.

10. Building và Publishing

Build: poetry build creates wheel và source distribution.

Publish: poetry config pypi-token.pypi your-token, then poetry publish --build.

TestPyPI: Test trước với poetry publish -r testpypi.

11. Integration với Development Tools

pyproject.toml là single config cho tất cả tools: Poetry, pytest, mypy, ruff, black, coverage.

Example workflow:

poetry new my-api && cd my-api
poetry add fastapi uvicorn
poetry add --group dev pytest mypy ruff
poetry run pytest
poetry run mypy .
poetry run ruff check .

12. Best Practices

✅ Do's:

  • Commit poetry.lock cho applications
  • Use version constraints wisely (^2.28)
  • Separate dev và prod dependencies
  • Use pyproject.toml cho all tool config
  • Pin Python version explicitly

❌ Don'ts:

  • Don't commit poetry.lock cho libraries
  • Don't use wildcard versions (*)
  • Don't mix pip và poetry
  • Don't edit poetry.lock manually
  • Don't ignore dependency conflicts

13. Common Commands Reference

# Project Management
poetry new project-name
poetry init
poetry install
poetry update
 
# Dependencies
poetry add package
poetry add --group dev package
poetry remove package
poetry show --tree
 
# Environment
poetry shell
poetry run command
poetry env info
 
# Building & Publishing
poetry build
poetry publish
poetry version patch/minor/major

Summary

Trong guide này, bạn đã học:

✅ Cài đặt và configuring Poetry
✅ Creating và managing Python projects
✅ Dependencies với version constraints
✅ Lock files cho reproducible builds
✅ Virtual environment management
✅ Dependency groups và extras
✅ Building và publishing packages
✅ Integration với development tools
✅ Best practices cho professional projects

Poetry là modern standard cho Python project management. Nó eliminates complexity của pip + requirements.txt + setuptools + venv bằng cách provide single, unified tool.

Bước Tiếp Theo

Giờ bạn đã hiểu Poetry, khám phá các chủ đề liên quan:

Áp Dụng Kiến Thức:

Thêm Python Deep Dives:

Quay Lại Roadmap:


Thuộc chuỗi bài Lộ Trình Học Python

📬 Đăng ký nhận bản tin

Nhận những bài viết mới nhất qua email mỗi tuần. Không spam, hủy đăng ký bất cứ lúc nào.

Chúng tôi tôn trọng quyền riêng tư của bạn. Hủy đăng ký bất cứ lúc nào.

💬 Comments

Đăng nhập để bình luận

Chúng tôi sẽ không đăng bất cứ điều gì mà không có sự cho phép của bạn.