Dependency sandboxing with virtualenv
So you have installed all the packages you want for your new project. Great! But, what happens when we develop the second project some time later that will use newer versions of the same packages? What happens when a library that you wish to use depends on a library you installed for the first project, but it uses an older version? When newer versions of packages contain breaking changes, upgrading them will require extra development work on an older project that you may not be able to afford.
Thankfully, there is virtualenv, a tool that sandboxes your Python projects. The secret to virtualenv is tricking your computer into looking for and installing packages in the project directory rather than in the main Python directory, which allows you to keep them completely separate.
Now that we have pip, to install virtualenv just run this:
$ pip install virtualenv
virtualenv basics
Let's initialize virtualenv for our project as follows:
$ virtualenv env
The extra env
tells virtualenv
to store all the packages into a folder named env
. virtualenv requires you to start it before it will sandbox your project:
$ source env/bin/activate # Your prompt should now look like (env) $
The source
command tells Bash to run the script env/bin/activate
in the context of the current directory. Let's reinstall Flask in our new sandbox as follows:
# you won't need sudo anymore (env) $ pip install flask # To return to the global Python (env) $ deactivate
However, it goes against the best practices in Git to track what you don't own, so we should avoid tracking the changes in third-party packages. To ignore specific files in our project, the gitignore
file is needed.
$ touch .gitignore
touch
is the Bash command to create files, and the dot at the start of a file tells Bash to not list its existence unless specifically told to show hidden files. We will create the simple gitignore
file for now:
env/ *.pyc
This tells Git to ignore the entire env
directory and ignore all the files that end with .pyc
(a compiled Python file). When used in this way, the *
character is called a wildcard.