CodeBlanks Logo Icon CodeBlanks

Virtual environment

Learn to create virtual environments with venv.

Virtual environment

A virtual environment creates a separate Python directory for a project. Packages installed there do not pollute the global Python; each project gets its own dependency tree.

python -m venv .venv

The command creates a fresh Python copy in the .venv/ directory. When activated, pip install writes only into this directory and leaves global packages untouched.

venv.EnvBuilder

venv.EnvBuilder is the class that creates a virtual environment from Python code. The with_pip=True parameter also installs pip; clear=True wipes an existing directory.

import venv

builder = venv.EnvBuilder(with_pip=True)
builder.create(".venv")

EnvBuilder does the same job as the python -m venv command line, but it can be called from scripts. This is handy for writing automated setup commands.

Practice Print the type of the EnvBuilder object

Start with import venv. Create a builder object with builder = venv.EnvBuilder(with_pip=False). Print the class name of the object with print(type(builder).__name__).

Starter code

main.py
# bring in the venv module
# create an EnvBuilder with with_pip=False
# print the class name of the builder object

Sample solution

main.py
import venv

builder = venv.EnvBuilder(with_pip=False)
print(type(builder).__name__)

Expected output

EnvBuilder

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does python -m venv .venv do?

  • Creates a virtual environment Correct answer
  • Builds a wheel
  • Uploads the package to PyPI
  • Freezes dependencies

Explanation: The venv command creates a virtual environment in .venv.

2 Complete the EnvBuilder call

Question
import venv

builder = venv.____(with_pip=True)
Answer
import venv

builder = venv.EnvBuilder(with_pip=True)

Explanation: EnvBuilder is the class that creates virtual environments.

3 Match the venv concepts

Term Meaning
venv Virtual env module
EnvBuilder Class that builds envs
with_pip Also installs pip
.venv Env directory

All lessons in Advanced