Python Virtual Environments: Setup and Isolation Explained

    This article explains why dependency conflicts happen when multiple projects share a single global Python installation, and how virtual environments solve the problem. It covers how Python resolves modules through sys.path, the directory structure of a virtual environment and the role of pyvenv.cfg, commands to create, activate, and remove environments, the correct use of the module search path variable, dependency pinning with requirements.txt for reproducibility, common troubleshooting cases, and engineering practices such as one environment per project and installing dependencies at image build time.

    1. Where the Problem Starts: Why Dependency Conflicts Keep Coming Back

    A developer maintaining three projects at once usually runs into the same frustration: project A needs an older version of a library, project B requires a newer one, and the system has only a single copy installed. Satisfying one project immediately breaks the other with an import error or an incompatible interface. Switching between projects therefore means readjusting the global dependencies every time, which is slow and hard to reproduce.

    The root cause is not the package manager itself, but the assumption of a “single global copy.” The operating system level interpreter and the third-party package directory are shared by every project, and sharing means there is no isolation boundary at all. That boundary is exactly what a virtual environment provides: each project gets its own view of dependencies, invisible to and undisturbed by the others.

    2. First, Understand How Modules Are Located

    Understanding isolation requires understanding the lookup order. Installing an interpreter normally gives you three things: the interpreter itself, which executes bytecode; the standard library (modules for system interaction, path handling, and so on); and a shared directory that holds third-party packages.

    When the interpreter starts, it builds a sequence of module search paths, which you can inspect like this:

    1. import sys
    2. for p in sys.path:
    3. print(p)

    The order of this list decides which copy of a same-named module ultimately wins. A typical order is: the directory containing the current script or the current working directory, extra directories specified by an environment variable, the standard library directory, and the shared third-party package directory. Once the shared directory comes first and a new version is written into it, every project is affected — that is the path along which conflicts propagate.

    One common misunderstanding is worth clearing up: a virtual environment does not fully copy the interpreter and the standard library. It is only a lightweight directory structure that reconfigures the interpreter’s “field of view.”

    3. Virtual Environment Directory Structure and How It Works

    After creating an isolated environment, the layout looks roughly like this:

    1. my_project_env/
    2. ├── bin/ # Unix-like systems; Scripts/ on Windows
    3. │ ├── python # link to the base interpreter
    4. │ ├── pip
    5. │ └── activate # activation script
    6. ├── lib/
    7. │ └── python3.x/
    8. │ └── site-packages/ # third-party packages for this environment only
    9. └── pyvenv.cfg # environment config: base interpreter location and whether system packages are inherited

    pyvenv.cfg is the key piece. It declares the path to the base interpreter and states whether the system-level package directory is enabled. On startup the interpreter reads this file and moves lib/python3.x/site-packages to the front of the search path, so the resolution of same-named modules is rewritten and isolation takes effect. Because the standard library and the interpreter itself still come from the base installation, creation is fast and the disk footprint is small.

    4. Creating, Activating, and Exiting

    Create:

    1. python -m venv my_project_env

    Activate (Unix-like systems):

    1. source my_project_env/bin/activate

    Activate (Windows command prompt):

    1. .\my_project_env\Scripts\activate

    What the activation script does is not mysterious; the core is three things: it prepends the environment’s executable directory to the command search path so that python and the package installation commands resolve to the copies inside the environment first; it sets an environment identifier variable that displays the environment name in front of the prompt as a reminder that you are currently isolated; and it adjusts the appearance of the command prompt.

    Exit and delete:

    1. deactivate # leave the current environment
    2. rm -rf my_project_env # delete the environment, equivalent to uninstalling all its dependencies

    “Deleting the directory is uninstalling” is the most practical property of virtual environments from an engineering standpoint: when an environment is broken or its dependencies are hopelessly tangled, rebuilding costs far less than cleaning up by hand.

    5. Using the Search Path Variable Correctly

    One variable is frequently misused: the environment variable that specifies extra module search directories. Its role is to “supplement paths,” which suits temporarily attaching a small number of directories — for example, pointing at a source directory that has not been packaged and installed yet, for debugging. It is not suited to dependency isolation, for three reasons: it takes effect globally, applying to every interpreter process for that user; it is inherited by child processes, which easily causes hard-to-trace overrides across multiple layers of calls; and the position it inserts into may sit ahead of the environment’s own package directory, breaking isolation instead.

    The recommended principle is therefore: leave isolation to virtual environments and path supplementation to that variable, and do not mix the two. To determine which copy of a module is actually loaded, the reliable approach is to print the module object’s file location:

    1. import some_module
    2. print(some_module.__file__)

    6. Recording Dependencies and Reproducibility

    An environment only solves “works on this machine.” Team collaboration and deployment additionally require “the same result on another machine.” The common approach is to write dependencies into a text manifest and restore from it:

    1. pip install -r requirements.txt # install from the manifest
    2. pip freeze > requirements.txt # export current exact versions

    More rigorous projects constrain the versions of both direct and transitive dependencies, avoiding behavior drift caused by upstream minor version changes.

    7. Troubleshooting Common Issues

    • Packages still install globally after activation: the package installation command was not taken over by the environment directory; check whether the command search path was successfully prepended.
    • Command not found: usually caused by not activating, or by restricted execute permission on the activation script; you can switch to invoking the interpreter as a module to install.
    • Environment size growing abnormally: usually model files or datasets were placed inside the environment directory; the environment should hold code dependencies only.
    • Editor reports import failures: in most cases the interpreter has not been switched to the one inside the environment, and it needs to be re-specified on the editor side.

    8. Engineering Recommendations

    A stable practical route is: one environment per project, with the environment directory kept inside the project and excluded from version control; the dependency manifest committed but the environment itself not; in the CI pipeline, create a fresh environment for every build and install from the manifest, guaranteeing “reproducible from zero”; for containerized deployment, fix dependency installation at the image build stage so the runtime environment is immutable. If the team uses a cloud container platform or a build service, dependencies should likewise be baked into the image or the build cache rather than installed temporarily at runtime.

    At this point the full chain is closed: from the module search path to the directory structure, then to creation, activation, dependency pinning, and troubleshooting. Once you have it, running multiple projects in parallel no longer requires repeatedly readjusting global dependencies, and the environment itself becomes a versionable, rebuildable engineering asset.