Using venv, pyvenv, autoenv on macOS
At some point, you might work on a Python project that requires specific dependencies, such as a machine learning project with an exact PyTorch version. It becomes a necessity to structure your workflow in order to avoid conflicts and iterate quickly across projects.
In this post I will explain the main tools that I use on macOS and show a neat trick in order to switch virtual environments automatically.
Why Use Virtual Environments?
The ability to replicate environments not only makes onboarding easier but also minimizes the « works on my machine » issue. To accomplish our goal, we will need three tools: pyenv, venv, and autoenv.
Pyenv
Pyenv is an incredible tool that allows you to switch between multiple versions of Python. You can even search and install Python versions and set local and global versions.
Venv
Venv is a built-in and simple method for creating isolated Python environments. While pyenv (through pyenv-virtualenv) could be used for isolating projects you should use venv.
Autoenv
Autoenv is magical tool that just makes using virtual environments seamless and uses .env and .env.leave files to activate and deactivate environments.
Setting up the tools
The tools require homebrew or another package manager and the ability to modify your shell.
We first need to install pyenv:
Then, we need to append the following lines to our .zshrc file:
You can refer to the documentation but the minimal commands are:
Finally we need autoenv:
Then executing the following in your zsh shell:
Before using the tool you should read the documentation and activate the « AUTOENV_ENABLE_LEAVE » option by setting it to any non empty string.
Practical workflow
Create or clone your project:
Set with pyenv the local python version needed:
Create the virtual environment:
Add the .env and .env.leave and approve the autoenv changes:
Conclusion
You are now ready to start your development with a clean and isolated environment!
If you found this guide useful you can also check the previous ones about Setting up macOS for development and AI Homelab: A guide into hardware to software considerations.