DEV Community

Cover image for Dependency management in Python
Stefan Alfbo
Stefan Alfbo

Posted on

Dependency management in Python

There is always a good practice to keep track of your dependencies in a project, no matter programming language.

This will make it much easier to share (open source), set up a CI/CD pipeline, security analysis of the project or just to restore the development environment.

All programming languages have their own way to solve this tracking issue of external packages/libraries.

The recommended way in Python is to use a requirements.txt file together with pip (Package Installer for Python).

Typical workflow:

# Install some python package(s)
python -m pip install flask

# Output installed packages in requirements format,
# packages are listed in a case-insensitive sorted order.
python -m pip freeze > requirements.txt

# Later when you need to reinstall all packages you use 
# this command.
python pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

It becomes a little bit cumbersome if you want to split up your package dependencies on what is needed in production and what is needed for developing the application.

The requirements.txt file can have any valid file name, so we can use that property and add another file to our project, requirements_dev.txt. That way you can keep the packages that is only needed for development (like pytest) in one file and everything else that is needed for production is in the requirements.txt file.

There is more to learn in the great documentation of pip.

Top comments (0)