Never Forget Your Virtual Environment Again

programming python virtual environment

Posted: 2023-02-03

When I started my journey in Python I had no idea what a virtual environment was. Learning installing packages through pip install, I unknowingly added all packages from all my different projects to the base Python environment. This was until I stumbled upon a package conflict between two of my projects. I started wondering whether I would have to reinstall different package versions depending on the projects I felt like working on that day.

Of course, Python had an answer to my problem with virtual environments. People on the internet often debate if one should use venv or virtualenv to create your virtual environments. Starting out I went with venv since it is already included in the Python standard library and I would recommend the same to newcomers unless you explicitly require some of the virtualenv features.

However, I quickly ran into a frustrating part of working with a virtual environment. I often forgot to activate and deactivate it during programming sessions! This had me installing packages all over the place and running into situations where I thought I had installed a package to a project but noticed I was still left in a virtual environment from another project. sigh

I found some workarounds using bash scripting or a separate python script but none of them where particularly satisfactory. And then I found it.

direnv

direnv is a linux package which hooks into your shell and loads environment variables depending on your current working directory. This means it will automatically activate and deactivate you python virtual environment when cd-ing into our out of your python project. Setting it up for a python project is very easy since it has a preset configuration where it uses venv to configure the environment.

  1. See their website for how to install and hook the package into your shell.
  2. cd to your python project directory.
  3. direnv edit . and add the following:
layout python [path_to_python_executable]
  1. Save the file and reload the terminal.

Congratulations! You should now see the following terminal output when cd-ing into and out of the directory.

> cd ~/python_project
direnv: loading ~/python_project/.envrc
direnv: export +VIRTUAL_ENV ~PATH

> cd ..
direnv: unloading

That would be all for today. I hope this was helpful!

Cheers,
Theo