Skip to content

Virtual environments (venv)

What is a venv?

A Python virtual environment (venv) is "created on top of an existing Python installation [...] and may optionally be isolated from the packages in the base environment". Each venv will have its own set of Python packages, indepedent from the the main Python installation.

It allows us to avoid this mess (from xkcd-1987):

How to create and use a venv

venv are builtin Python, and you can install a venv in a specific folder. In the folder where you have some code, you can create a new venv:

python -m venv ./myenv

For Windows, replace ./myenv by the path where you want the venv.

Then the venv needs to be activated, how to do this depends on your OS and used console:

If you're still in the folder above, with macOS I need to:

source ./myvenv/bin/activate

The new venv you created is empty, that is it should only have 2 packages as shown in the console above. You can install new packages with pip install numpy and those will be added in the venv. As long as you see the name of your venv between brackets ((myenv)) it means that you are using the venv.

To stop using this venv:

deactivate

PyCharm allows you to create venv and activate them, follow those instructions:

In a specific folder, you can do uv init and this will create a virtual environment (and a file pyproject.toml).

To install a package, instead of pip install, you have to uv add XXX to add the XXX package.

Then to run a script, you should uv run myscript.py

That's it.