The Right Way to Use Virtual Environments
Separate the environment from the source code
For a long time, Python developers used virtualenv to create sandboxed projects. With Python 3.4 and higher, they can use the native pyvenv package to do the same thing.
Get JT Paasch’s stories in your inbox
Join Medium for free to get updates from this writer.
But many of the examples and tutorials encourage a bad practice. There’s a better way to do it.
The bad way
- Make a virtual environment:
pyvenv myproject- This is equivalent to creating a folder for your project…
mkdir myproject && cd myproject- …and then converting it into a virtual environment:
pyvenv .- This installs the virtual environment folders inside your project’s root. Now you can activate it and use it:
source bin/activateThe good way
- Make a project folder:
mkdir myproject && cd myproject- Now create the virtual environment inside its own folder. Call it venv or env or something obvious:
pyvenv venv- Put the venv in your .gitignore:
git init
echo 'venv' > .gitignore- This keeps your virtual environment out of source control.
- Activate the environment:
activate venv/bin/activate- Install something:
pip install django- Freeze the requirements:
pip freeze > requirements.txt- Check requirements.txt into source control:
git add requirements.txt- The basic idea here is simple. Your virtual environment stays in its own folder, which you don’t check into source control. That way your environment does not pollute your project’s root. The requirements, on the other hand, do get checked into source control.






