Explain Codes LogoExplain Codes Logo

Using Python 3 in virtualenv

python
virtualenv
python-3
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 15, 2024
TLDR

To use Python 3 inside a virtualenv, run the following:

virtualenv -p `which python3` env source env/bin/activate # On Unix env\Scripts\activate # On Windows

This creates and starts a Python 3 virtual environment named env tailored for your project's dependency isolation.

If you have Python 3.6 or newer, venv is already included out of the box:

python3 -m venv env source env/bin/activate # On Unix env\Scripts\activate # On Windows

If you get compatibility issues, upgrade virtualenv like so:

pip install --upgrade virtualenv

You can deep dive into specific issues related to virtualenv like #463.

Setting up like a Python Pro

Handling Python versions with pyenv

When dealing with multiple Python versions, supplement pyenv-virtualenv with pyenv for better navigation:

pyenv install 3.8.6 # Download Python 3.8.6 pyenv virtualenv 3.8.6 my-env # Create a new virtualenv using Python 3.8.6

To activate:

pyenv activate my-env # Welcome home!

To ensure you're using the intended Python version, do a quick check:

python --version # Version check! Are we on the same page, Python?

Streamlining with virtualenvwrapper

To enhance your workflow, use virtualenvwrapper, essentially the Swiss Army knife of virtual environments:

  • Make a new virtualenv with:
mkvirtualenv -p `which python3` my-env # Python 3, meet my-env!
  • Visit an existing virtual environment:
workon my-env # Okay my-env, let's get back to work!

Utilizing system-wide packages

Occasionally, you might need those system packages. Here's what you do when setting up the virtualenv:

virtualenv --system-site-packages my-env # System packages? Invite them over!

Always check for compatability and performance issues, because not everyone plays nice together.

Tackling compatibility issues on macOS

For macOS users, go with venv to avoid compatibility issues:

python3 -m venv my-env # venv, macOS's favorite party guest!

If you encounter problems, raise an issue on virtualenv's GitHub repository because sharing is caring.

Keeping global packages on call

For packages you often use, give them a global pass and use them in multiple virtual environments. Just be discerning with project-specific dependencies.