In this lesson, you will learn how to lock your project’s exact dependency versions to ensure your application behaves identically on your local machine, your colleague’s computer, and your production server.
The Problem: The "Works on My Machine" Syndrome
When you install packages using pip install requests, pip fetches the latest compatible version. If you run this command today, you might get version 2.31.0. However, if your teammate runs it in a month, they might receive version 2.32.0. If that new version introduces a breaking change or a hidden bug, your application might crash in production even though it passed all tests locally.
The Solution: Freezing
To prevent this, we "freeze" our environment. Freezing creates a snapshot of the exact versions of every package currently installed in your virtual environment.
You can generate this snapshot by running:
pip freeze > requirements.txt
This command scans your active environment and writes a list of every package and its specific version—e.g., requests==2.31.0—into a file named requirements.txt.
Utilizing the Snapshot
Once you have this file committed to your version control system (like Git), anyone who downloads your project can reconstruct your exact environment. Instead of manually installing packages, they run:
pip install -r requirements.txt
This tells pip to read the list and install the precise versions specified. By using == operators, you remove ambiguity from the installation process. Even if a library author releases a buggy update tomorrow, your deployment remains locked to the stable version you verified during development.
It is important to remember that pip freeze includes all sub-dependencies. This might look noisy, but it is the key to creating a deterministic environment. By strictly controlling your dependency tree, you transform a potentially brittle setup into a robust, professional-grade deployment pipeline.
Key Takeaway: Use pip freeze > requirements.txt to lock exact dependency versions, ensuring that your production environment is a perfect mirror of your tested development environment.