The Right Way to Use Virtual Environments

JT Paasch
JT Paasch
Oct 24, 2014 · 1 min read

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.

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/activate

The 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.

    JT Paasch

    Written by

    JT Paasch

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade