Table of Contents

    Creating Packages

    CHAPTER 28.4 · PYTHON PACKAGE MANAGEMENT

    Virtual Environment in Python

    Learn how to create, activate, use, deactivate, and recreate an isolated Python environment using the built-in venv module.

    Different Python projects may require different packages or different versions of the same package. Installing every dependency into one global Python installation can create package conflicts.

    A virtual environment provides a separate Python environment for an individual project. Packages installed in one virtual environment do not normally affect packages installed in another environment.

    Learning objective: In this tutorial, you will learn why virtual environments are important, how to create and activate them, and how to install project-specific packages safely.

    Prerequisites

    What You Need

    • Python 3 should be installed on your computer.
    • Python should be accessible from Command Prompt, PowerShell, Terminal, or another command-line shell.
    • You should understand basic terminal commands such as cd.
    • Basic knowledge of pip and Python package installation is helpful.
    • A separate project folder should be available.

    What is a Virtual Environment?

    A virtual environment is a project-specific Python environment. It contains a Python executable, activation scripts, configuration information, and a separate location for installed packages.

    Python provides the built-in venv module for creating lightweight virtual environments.

    Think of it as a separate toolbox

    Every project receives its own toolbox containing the exact packages and versions it needs. Updating one toolbox does not change the contents of another.

    Why Use a Virtual Environment?

    Without a Virtual Environment

    • Unrelated projects may share the same packages.
    • Upgrading a package may unexpectedly affect another project.
    • Project-specific dependencies become difficult to identify.
    • Reproducing the project environment becomes harder.

    With a Virtual Environment

    • Each project maintains its own dependencies.
    • Different projects can use different package versions.
    • Package changes remain isolated to the selected project.
    • The environment can be recreated from a dependency file.

    Example of a Version Conflict

    Suppose two Python projects require different versions of the same package:

    Project Package Required Version
    Project A Django Version 4.x
    Project B Django Version 5.x

    Separate virtual environments allow both projects to use their required versions without interfering with each other.

    Check the Python Installation

    Open your command-line application and check the installed Python version.

    python --version

    On some systems, use one of the following commands:

    py --version
    python3 --version

    Example output:

    Python 3.x.x

    Create a Project Folder

    First, create a separate folder for the Python project:

    mkdir virtual-environment-demo

    Move into the project folder:

    cd virtual-environment-demo

    Create a Virtual Environment

    Use the following command to create an environment named .venv:

    python -m venv .venv

    On Windows, the Python launcher may also be used:

    py -m venv .venv

    On Linux or macOS, you may need to use:

    python3 -m venv .venv
    .venv is a commonly used environment directory name. Other names such as venv or project-env may also be used.

    What Does venv Create?

    The venv module creates a directory containing the files needed for the isolated Python environment.

    Environment Item Purpose
    Python executable Runs Python using the selected environment.
    Activation scripts Configure the current shell to use the environment.
    Package directory Stores packages installed for the project.
    Configuration file Stores information about the virtual environment.

    Activate the Virtual Environment

    Activation configures the current terminal to use the virtual environment's Python interpreter and package installation location.

    Windows Command Prompt

    .venv\Scripts\activate

    Windows PowerShell

    .venv\Scripts\Activate.ps1

    Linux or macOS

    source .venv/bin/activate

    After activation, the environment name normally appears before the terminal prompt:

    (.venv) project-folder
    Activation does not create a virtual machine. It configures the current terminal to use the selected Python environment.

    Verify the Active Environment

    Use Python to display the active interpreter location:

    python -c "import sys; print(sys.executable)"

    The displayed location should contain the .venv directory.

    Verify the pip installation:

    python -m pip --version

    The pip location should also belong to the active environment.

    Install Packages in the Environment

    After activating the environment, install the required package:

    python -m pip install requests

    Install multiple packages:

    python -m pip install requests flask pytest

    Display the installed packages:

    python -m pip list

    Check package compatibility:

    python -m pip check

    Successful compatibility check:

    No broken requirements found.

    Test the Environment

    Create a file named app.py:

    import requests
    
    print("Requests version:", requests.__version__)
    print("Virtual environment is working.")

    Run the program:

    python app.py

    Possible output:

    Requests version: 2.x.x
    Virtual environment is working.

    Save the Project Dependencies

    Generate a requirements file containing the packages installed in the environment:

    python -m pip freeze > requirements.txt

    Example requirements.txt:

    certifi==2025.4.26
    charset-normalizer==3.4.2
    idna==3.10
    requests==2.32.3
    urllib3==2.4.0

    The dependency file can be used to recreate the environment on another computer.

    Exclude the Environment from Git

    The environment directory should not normally be committed to a version-control repository.

    Add the following entry to the project's .gitignore file:

    .venv/
    __pycache__/
    *.pyc

    Do Not Commit

    • The complete virtual environment directory
    • Environment executables
    • Installed package files
    • Generated Python cache files

    Commit These

    • Project source code
    • requirements.txt
    • pyproject.toml when used
    • .gitignore

    Deactivate the Environment

    When you finish working on the project, leave the environment using:

    deactivate

    Deactivation does not delete the environment or remove its installed packages. It only returns the current terminal to its normal Python configuration.

    Reactivate an Existing Environment

    You do not need to create the environment again every time you open the project.

    Navigate to the project folder and run the appropriate activation command:

    .venv\Scripts\activate

    For Linux or macOS:

    source .venv/bin/activate

    Recreate a Virtual Environment

    A virtual environment should be considered reproducible. Instead of copying the complete environment directory, create a new environment and reinstall the recorded dependencies.

    RECREATION WORKFLOW
    Source Code + requirements.txtNew Virtual Environment

    Create a new environment:

    python -m venv .venv

    Activate the environment and install the requirements:

    python -m pip install -r requirements.txt

    Verify the installed dependencies:

    python -m pip check

    Common Problems and Solutions

    1

    Python Command Is Not Available

    The command used to start Python may differ between systems.

    Solution Try py on Windows or python3 on Linux and macOS. Verify that Python is installed.
    2

    Environment Does Not Activate

    The activation command may not match the operating system or command-line shell.

    Solution Use the activation command designed for your operating system and terminal application.
    3

    Package Cannot Be Imported

    The package may have been installed into a different Python environment.

    Possible Error ModuleNotFoundError
    Solution Verify the active interpreter and run python -m pip show package_name.
    4

    Wrong Environment Is Active

    The terminal may still be using another project's environment.

    Solution Run deactivate, open the correct project folder, activate its environment, and verify the interpreter path.

    Best Practices

    Recommended Practices

    • Create a separate environment for every project.
    • Use a clear environment name such as .venv.
    • Verify the active interpreter before installing packages.
    • Use python -m pip to run pip through the selected interpreter.
    • Save project dependencies in requirements.txt.
    • Add the environment directory to .gitignore.
    • Recreate a damaged environment instead of manually modifying its internal files.
    • Follow organizational security, licensing, and package-use policies.

    Complete Workflow

    # Create the project folder
    mkdir virtual-environment-demo
    
    # Enter the project folder
    cd virtual-environment-demo
    
    # Create the environment
    python -m venv .venv
    
    # Activate the environment using the command for your system
    
    # Verify Python
    python -c "import sys; print(sys.executable)"
    
    # Verify pip
    python -m pip --version
    
    # Install packages
    python -m pip install requests flask pytest
    
    # List packages
    python -m pip list
    
    # Check dependencies
    python -m pip check
    
    # Save dependencies
    python -m pip freeze > requirements.txt
    
    # Leave the environment
    deactivate

    Knowledge Check

    1

    What is a virtual environment?

    It is an isolated Python environment that maintains project-specific packages and versions.

    2

    How do you create an environment?

    python -m venv .venv
    3

    How do you activate it on Linux or macOS?

    source .venv/bin/activate
    4

    How do you leave the environment?

    deactivate
    5

    Should the environment directory be committed to Git?

    No. Commit the project source and dependency file instead of the complete environment directory.

    Virtual Environment Quick Reference

    # Create an environment
    python -m venv .venv
    
    # Activate on Linux or macOS
    source .venv/bin/activate
    
    # Display the active interpreter
    python -c "import sys; print(sys.executable)"
    
    # Verify pip
    python -m pip --version
    
    # Install a package
    python -m pip install requests
    
    # Install from requirements.txt
    python -m pip install -r requirements.txt
    
    # List packages
    python -m pip list
    
    # Check dependencies
    python -m pip check
    
    # Save dependencies
    python -m pip freeze > requirements.txt
    
    # Leave the environment
    deactivate

    Summary

    What You Learned

    • Virtual environments isolate packages between projects.
    • Python's built-in venv module creates virtual environments.
    • Activation configures the current terminal to use the environment.
    • Packages installed in the active environment remain project-specific.
    • The environment directory should not be committed to version control.
    • A dependency file can be used to recreate the environment.
    • Deactivation leaves the environment without deleting it.

    Key Takeaway

    Create a separate virtual environment for each Python project. Verify the active interpreter, install only the packages required by the project, record those dependencies, and recreate the environment when necessary.