Managing Python Virtual Environments
If you work on more than one Python project, you know the pain of dependency conflicts. Project A needs Django 3.2, while Project B is still stuck on Django 2.2. If you install everything globally, you are asking for trouble.
I've tried a few different tools over the years, and here is my current workflow.
The Standard Way: venv
Python 3 has built-in support for virtual environments. It's simple and doesn't require installing any extra packages.
# Create the environment
python3 -m venv myenv
# Activate it (Linux/macOS)
source myenv/bin/activate
# Activate it (Windows)
myenv\Scripts\activate
When you are done, just type deactivate. It works well, but you have to remember to activate it every time you open a new terminal window.
My Preference: pipenv
Recently, I've started using pipenv. It combines pip and venv into one tool and uses a Pipfile instead of a requirements.txt.
The main advantage is that it manages the environment automatically. I just navigate to my project folder and type:
pipenv shell
If the environment doesn't exist, it creates it. If it does, it activates it. It also keeps track of exactly which packages are installed and their dependencies, which makes reproducing the environment on a server much easier.
A word of caution
Don't commit your virtual environment folders (like myenv/ or .venv/) to Git. It will bloat your repository and cause issues for anyone else trying to run your code. Always add them to your .gitignore file.