Virtual environments#

Learning Objectives#

  • Understand the importance of using virtual environments in Python development

  • Differentiate between various tools for managing virtual environments: venv, Conda, Pipenv, and Poetry

  • Create and activate a virtual environment using venv

  • Use Conda to manage environments and packages

  • Utilize Pipenv and Poetry for dependency management and virtual environments

Why do we need virtual environments?#

Control#

Virtual environments give you control over the version of Python and the versions of installed libraries (modules). Typically this means you will be using the latest versions of Python and libraries for your latest project.

Freedom to update#

By using virtual environments you are free to update to new versions of libraries for your latest project, without breaking earlier projects.

Reliable deployment#

It is far easier to create reproducible and portable software with virtual environments.

System Python!#

Use of Python is so widespread that some operating systems include Python, for a long time this was Python 2.7 though more recently Python 3 (3.8,3.9) has become a popular default. It is never a good idea to change this configuration, except with the usual system upgrade tools.

Why not use virtual machines or containers?#

These have their own place in development and deployment of software. We are not going to cover them here, except to note -

If you find yourself having to do complicated or unusual things with virtual environments, or virtual environments do not provide the facilities or security your software requires, then consider alternatives such as Docker.

Yes, but#

I have admin rights so I can install libraries and new Python version for all users.

Just don’t!

venv#

Tutorial https://docs.python.org/3/tutorial/venv.html

python -m venv .venv

source .venv/bin/activate

Though in practice your IDE, e.g. VS Code will typically activate environments for you.

Conda#

https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html

Pipenv#

mkdir .venv
pipenv install numpy
pipenv shell

Poetry#

https://python-poetry.org/docs/

pipx install poetry

https://python-poetry.org/docs/basic-usage/