Virtual Environment Mechanics (venv & sys.prefix)
A Python virtual environment is not a hardware hypervisor. It is a lightweight folder containing binary symlinks, a `pyvenv.cfg` configuration marker, and an isolated `site-packages/` directory redirected via `sys.prefix` 🌲.
import sys
# Detect active virtual environment:
in_virtualenv = sys.prefix != sys.base_prefix
print(f"Inside venv: {in_virtualenv} 🌲")
print(f"Prefix: {sys.prefix}")
print(f"Base Prefix: {sys.base_prefix}")
# 93. Virtual Environment Mechanics (venv & sys.prefix) A Python virtual environment is not a hardware hypervisor. It is a lightweight folder containing binary symlinks, a `pyvenv.cfg` configuration marker, and an isolated `site-packages/` directory redirected via `sys.prefix` 🌲. ```python import sys # Detect active virtual environment: in_virtualenv = sys.prefix != sys.base_prefix print(f"Inside venv: {in_virtualenv} 🌲") print(f"Prefix: {sys.prefix}") print(f"Base Prefix: {sys.base_prefix}") ``` Modern package managers like `uv` create virtual environments in milliseconds by hard-linking or reflinking cached Python binaries directly, bypassing slow disk copies entirely ⚡! --- ### Question How does the Python executable determine whether it is running within a virtual environment? 🧠- [ ] a. It detects a `pyvenv.cfg` file adjacent to the binary, redirecting `sys.prefix` to the venv directory 🌲 - [ ] b. It queries the system systemd init daemon for virtual environment namespace tags - [ ] c. It evaluates CPU virtualization flags via kernel hardware registers - [ ] d. It checks whether environment variable `PYTHON_IS_VENV` equals 1 --- ### Challenge Check whether `sys.prefix` and `sys.base_prefix` are valid `str` instances. Print `True` if both are strings. 🎯 <details> <summary>Solution</summary> ```python import sys print(isinstance(sys.prefix, str) and isinstance(sys.base_prefix, str)) ``` </details>