Dealing with dependancies in Python
Application dependencies are libraries — other than those that are a part of your project code — required to build and run your application. When working on a collaborative project, managing dependencies becomes essential.
This EdPresso shot walks you through the use of conda
to manage dependencies for an application. It will show you how to install and use the necessary tools and make strong recommendations on best practices.
Motivation
First, let us generate a list of all packages that are a currently a part of our development environment.
1 | $ cd /PATH/TO/PROJECT |
Without a proper framework for dependency management, this is what one sees.
1 | alabaster==0.7.12 |
That’s a lot of packages. Now you might be wondering what kind of project uses so many libraries? The answer is no kind. At least from what I have seen. No Python project uses 400+ packages. So what is the reason this type of output? Well, this list includes all packages in the environment including those that you do not use in your current project.
This is not the right way to deal with application dependancies. We can’t give this list to our users. There’s no need to make everybody who wants to use this application download and install every single package we have on our system. We want to create a list of only those packages relevant that our application and we want that list to detail the correct versions of every package.
Using a virtual environment
A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated environments for them, containing only the required packages.
There are many ways to create virtual environments. In fact, every modern Python distribution has built-in creation capabilities. This tutorial will use conda.
Installation
1 | $ pip install conda |
Creating your first virtual environment
1 | $ conda create -n new_venv python=3.7 |
We just created a new virtual environment called new_venv
and specified that we’ll be using Python 3.7 with it — you can use any other version compatible with your project. Now let’s activate this environment and see our requirements.txt file.
1 | $ cd /PATH/TO/PROJECT |
So what does the new output look like?
1 | chardet==3.0.4 |
A much more concise version. Now we can supply this list to our users and all they have to do is install the listed packages.
1 | $ cd /PATH/TO/PROJECT |
Let there be light!