Lab 15: Virtual Environments & Packaging

🎯 Objective

Set up isolated Python environments, structure a real Python project, manage dependencies with pip and requirements files, and understand how professional Python projects are organized.

πŸ“š Background

Virtual environments isolate project dependencies β€” Project A can use Flask 2.0 while Project B uses Flask 3.0, with no conflicts. Without venv, every pip install goes into the system Python, creating "dependency hell." Professional Python projects follow conventions: src/ layout, requirements.txt, setup.cfg or pyproject.toml, and clear separation of code, tests, and configuration.

⏱️ Estimated Time

30 minutes

πŸ“‹ Prerequisites

  • Lab 14: Regular Expressions

πŸ› οΈ Tools Used

  • Python 3.12

  • pip

  • venv

πŸ”¬ Lab Instructions

Step 1: Creating and Using Virtual Environments

πŸ“Έ Verified Output:

πŸ’‘ The venv contains its own Python interpreter and pip. When activated, python and pip point to this isolated environment β€” system Python is untouched.

Step 2: Working Inside a Virtual Environment

πŸ“Έ Verified Output:

πŸ’‘ activate modifies your PATH so python and pip point to the venv. deactivate restores the original environment. In scripts, use the full path: /tmp/myproject_env/bin/python script.py.

Step 3: Installing and Managing Packages

πŸ“Έ Verified Output:

Step 4: Professional Project Structure

πŸ“Έ Verified Output:

Step 5: Installing as Editable Package

πŸ“Έ Verified Output:

Step 6: Running Tests with pytest

πŸ“Έ Verified Output:

Step 7: Environment Variables and .env Files

πŸ“Έ Verified Output:

Step 8: pip Best Practices

πŸ“Έ Verified Output:

βœ… Verification

Expected output:

🚨 Common Mistakes

  1. Installing without venv: Global pip installs conflict between projects β€” always use python3 -m venv .venv.

  2. Committing .env files: Contains secrets β€” always add .env to .gitignore.

  3. No requirements.txt: Other developers can't reproduce your environment β€” always pip freeze > requirements.txt.

  4. Using requirements.txt in production without pinning: flask (no version) can break; always pin: flask==3.0.2.

  5. Confusing pip install package vs pip install -e .: The -e flag installs your own project; plain install is for dependencies.

πŸ“ Summary

  • python3 -m venv .venv β€” create isolated environment; source .venv/bin/activate to use it

  • pip install -r requirements.txt β€” reproduce an environment; pip freeze > requirements.txt to save it

  • Professional structure: src/package/, tests/, pyproject.toml, .gitignore

  • pyproject.toml is the modern standard (replaces setup.py)

  • .env files store secrets β€” never commit; load with python-dotenv in production

  • Editable installs (pip install -e .) let you develop without reinstalling

πŸ”— Further Reading

Last updated