Dependency management in Python is the process of specifying and handling the external libraries and packages that your project depends on. Python uses package management tools to help with this, with the most common ones being pip
and virtualenv
(or venv
). Additionally, there are tools like pipenv
and poetry
that provide more advanced features and dependency resolution.
1. pip and requirements.txt:
- Installing Dependencies:
- Use
pip
to install dependencies listed in arequirements.txt
file.pip install -r requirements.txt
- Creating requirements.txt:
- Generate a
requirements.txt
file that lists all the dependencies and their versions.pip freeze > requirements.txt
2. virtualenv (or venv):
- Creating Virtual Environments:
- Use
virtualenv
(orvenv
in Python 3.3 and later) to create isolated environments for your projects.# Using virtualenv virtualenv venv # Using venv python -m venv venv
- Activating Virtual Environments:
- Activate the virtual environment.
# On Windows .\venv\Scripts\activate # On Unix or MacOS source venv/bin/activate
- Deactivating Virtual Environments:
- Deactivate the virtual environment.
deactivate
3. pipenv:
- Installation:
- Install
pipenv
usingpip
.pip install pipenv
- Managing Dependencies:
- Use
Pipfile
andPipfile.lock
to manage dependencies.# Install dependencies pipenv install # Install a specific package pipenv install package_name # Uninstall a package pipenv uninstall package_name
- Activating the Virtual Environment:
pipenv
automatically activates the virtual environment for you.# Shell within the virtual environment pipenv shell
4. poetry:
- Installation:
- Install
poetry
usingpip
.pip install poetry
- Managing Dependencies:
- Use
pyproject.toml
to manage dependencies.# Add a new dependency poetry add package_name # Remove a dependency poetry remove package_name
- Creating Virtual Environments:
poetry
automatically creates and manages the virtual environment.# Install dependencies and create virtual environment poetry install
- Activating the Virtual Environment:
- Use
poetry shell
to activate the virtual environment.poetry shell
These tools help you isolate your project’s dependencies, ensuring that it runs consistently across different environments. Choose the tool that best fits your workflow and project requirements. Many modern projects are moving towards using poetry
due to its simplicity and powerful features.