This guide explains virtual environments with venv: why they matter through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
Virtual environments isolate packages per project while sharing a base Python installation. They are the default starting point for most third-party dependency work.
When and Why to Use It
The following example focuses on a practical use of Virtual Environments with venv: Why They Matter.
Step-by-Step Example
# Terminal, from the project root:
# python3.15 -m venv .venv
# Windows: .venv\Scripts\python.exe -m pip --version
# macOS/Linux: .venv/bin/python -m pip --version
import sys
print(sys.prefix)
print(sys.base_prefix)
Understanding the Example
When run inside an active virtual environment, sys.prefix typically points to that environment while sys.base_prefix points to the underlying interpreter. Their exact paths depend on the machine.
Expected Output
/opt/pyvenv
/usr
Important Behavior and Edge Cases
Do not commit .venv to version control or assume a virtual environment changes the Python major/minor version.
Try It Yourself
Create two independent virtual environments and compare each interpreter’s sys.prefix values.
Run environment-management commands in your terminal, not in a Python source file. Use the executable associated with the selected project interpreter and verify the environment before installing dependencies.
Common Beginner Mistakes
- Do not commit .venv to version control or assume a virtual environment changes the Python major/minor version.
- Running installation commands against a different Python interpreter than the one used for the project.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- Virtual environments isolate packages per project while sharing a base Python installation.
- When run inside an active virtual environment, sys.prefix typically points to that environment while sys.base_prefix points to the underlying interpreter.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.