User Avatar

I write about freelancing, solopreneurship, web dev and data science.

The first thing most aspiring Pythonistas learn about managing Python dependencies is to run pip install <package_name> whenever they need a package that isn't present on their system, yet. This works and doesn't overcomplicate things when you're just getting started. However, when you're working on a serious project, there are a couple of things you should make sure to incorporate into your dependency management strategy as I will lay out below.

Use separate environments

When you pip install a package, the default location that package will end up in is the global Python environment on your machine. The more projects you work on, the higher the probability that this lands you in dependency hell.

Let's say you install package X and package Y and both of them depend on package Z. If the versions of package Z that package X accepts don't overlap the versions of package Z that package Y accepts, there is an unsolvable dependency conflict.

To diminish the risk of this happening, you should create a separate environment for each project you work on.

Document the dependencies

More than once, I have been onboarded to projects where only parts of the dependencies were documented or dependencies weren't documented at all. What I need to do in these cases is to run the code, wait for it to raise a "Module Not Found" exception, identify and install the corresponding dependency and repeat this until the code runs without error. As you can imagine, this is very annoying.

To make sure new project contributors can install all required dependencies before running the code, you need to write down all required dependencies in a file. This should be done in a format that can be used by a package manager to install them.

Lock direct and indirect dependencies

Direct dependencies of your project are the ones that you import into your code. Documenting these is a good first step to make sure what works on your machine also runs on your teammates' machines.

However, your direct dependencies have dependencies themselves. When you tell the package manager to install the direct dependencies, you can end up with a different set of indirect dependencies based on when you ran the installation. To make sure you, your teammates, and your production server all run the same exact code, you need to save a list of all direct and indirect dependencies including their exact version in a file and tell your package manager to install what's in the file.

Poetry makes all of this easy

There are many different package managers in the Python world. My favorite one is called Poetry. It makes all of the above points easy to achieve and automates the tedious parts. Give it a try!

You get bonus points if you add a README file to your project that describes how to install its dependencies.