nanyang-system-developers

Dependency Management

Overview

Dependency management is about using tools to handle the libraries and tools your project needs to run. Managing dependencies by hand—such as installing packages one by one or tracking versions in a text file—is error-prone and can easily lead to broken projects, version conflicts, or missing packages.

Tools like poetry and pip automate this process, making your code more reliable and easier to share and maintain.

Some pitfalls of managing dependencies by hand:

Why Is It Important?

Imagine you are building a Flask API for your college project. You need Flask, psycopg2 (for PostgreSQL), and maybe some other libraries. If you install everything globally, you might accidentally break another project that needs a different version of Flask or psycopg2. Or, if you share your code with a teammate, it might not work on their laptop because they have different versions installed.

Dependency management tools help you avoid these problems.

Key Concepts

Example: Why Dependency Management Matters

Suppose you are working on two projects:

If you install everything globally, installing one version of Flask will overwrite the other, causing one project to break. With proper dependency management (using virtual environments and lock files), each project gets exactly what it needs, and they don’t interfere with each other.

Setting Up Dependency Management with Poetry

Poetry is a modern tool for managing Python dependencies and virtual environments. It makes it easy to keep your project isolated and reproducible.

Starting a New Project with Poetry

  1. Open a terminal and navigate to your project folder (create one if it doesn’t exist):
    • On Windows:
      mkdir my-flask-api
      cd my-flask-api
      
    • On Mac/Linux:
      mkdir my-flask-api
      cd my-flask-api
      
  2. Initialize Poetry in your project:
    poetry init
    

    Poetry will ask you some questions. You can press Enter to accept the defaults.

  3. Add your dependencies (for example, Flask and psycopg2):
    poetry add flask psycopg2
    

    This creates a pyproject.toml (lists your dependencies) and a poetry.lock (records exact versions).

  4. To install all dependencies (if you get a project from GitHub or someone else):
    poetry install
    

Using the Virtual Environment

Keeping Environments in Sync

Best Practices

Further Reading