Search code examples
pythonpython-venv

How does creating a Python venv with `--system-site-packages` work under the hood?


I'm trying to understand how creating a Python venv with access to the system site-packages work. The documentation doesn't go much into details, so I've just checked the diff between two venvs with and without the --system-site-packages option. It seems that the difference is just in pyvenv.cfg:

@@ -1,5 +1,5 @@
 home = /usr/bin
-include-system-site-packages = true
+include-system-site-packages = false
 version = 3.12.8
 executable = /usr/bin/python3.12
-command = /usr/bin/python -m venv --system-site-packages /tmp/venv1
+command = /usr/bin/python -m venv /tmp/venv2

How does this make the system packages accessible in the virtual environment?


Solution

  • Passing --system-site-packages to venv does indeed just set include-system-site-packages = true in the pyvenv.cfg file. The rest is being done by the site module, which is imported automatically when the interpreter starts. This is documented a bit in PEP 405 (and the site module docs as well):

    By default, a virtual environment is entirely isolated from the system-level site-packages directories.

    If the pyvenv.cfg file also contains a key include-system-site-packages with a value of true (not case sensitive), the site module will also add the system site directories to sys.path after the virtual environment site directories. Thus system-installed packages will still be importable, but a package of the same name installed in the virtual environment will take precedence.