Modules and environments
Virtual environments and dependencies
Recognise when projects need isolated installed packages.
Lesson 42 of 63
Reading: about 2 min
Lesson + practice: about 13 min
Difficulty: Intermediate
On this page5 sections
A virtual environment gives a project its own Python executable and installed packages. Create one with python -m venv .venv, using your working Python 3 command in place of python if needed. You can run its interpreter directly without activating: on Windows PowerShell use ./.venv/Scripts/python.exe -m pip --version; on macOS or Linux use ./.venv/bin/python -m pip --version. Standard-library modules need no pip install.
Worked example
import sys
print(f"Interpreter: {sys.executable}")
print(f"Inside a virtual environment: {sys.prefix != sys.base_prefix}")With your base Python: Interpreter: <path to your Python> Inside a virtual environment: False With the .venv Python: Interpreter: <path to .venv Python> Inside a virtual environment: True
Why this works
The interpreter path varies by machine. The second line is False for a base interpreter and True for a virtual environment. Run this script with the interpreter inside .venv to see the difference.
Another case
from importlib.util import find_spec
print(find_spec("json") is not None)
print(find_spec("not_installed_example") is not None)True False
find_spec() checks whether the interpreter you are running can import a module. After installing a package into .venv, run this check with the .venv interpreter to confirm the package is available in that environment.
Practice
Create a venv in a disposable folder, then run this example once with the base interpreter and once with the interpreter inside .venv.
Check the practice result
Reveal answer
The paths differ. The second run reports True for the virtual-environment check; exact paths vary by operating system.
Try another case
You install a package with pip while .venv is active, then run your script with the base Python in another terminal. Will the import work?
Check your answer
Reveal answer
Usually not. The package was installed into .venv, and the base interpreter has its own separate packages. Run the script with the .venv interpreter.
Your progress
Reveal the check answer or reach the end to complete this lesson.