Virtual Environments & pip, Briefly
You'll learn to
- -Explain what a virtual environment is and why it isolates a project's dependencies
- -Use `pip install` to add a third-party package to a project
- -Know that none of this is needed inside the Forge Algorithm Lab sandbox itself
This chapter is intentionally short - it is a practical aside about the Python ecosystem outside of ScaleDojo, not a deep topic. The Forge Algorithm Lab's browser-based sandbox already has everything you need pre-installed and does not require (or allow) installing packages, so nothing here is required for lab levels. It matters for being a competent Python developer everywhere else.
The Problem: Every Project Wants Different Versions
If you work on two different Python projects on the same machine, they might need different versions of the same third-party library - one needs an old version, the other needs the newest. Installing packages globally, system-wide, means you cannot satisfy both at once. A virtual environment ("venv") solves this by giving each project its own private, isolated set of installed packages, completely separate from every other project on the machine.
Creating and Using a Venv
Once a venv is active, `pip install some-package` installs it only into that isolated environment - your other projects, and your system-wide Python, are unaffected. Deactivating (`deactivate`) returns you to your normal system Python.
A project's dependencies are usually recorded in a `requirements.txt` file (one package per line, e.g. `requests==2.31.0`), which lets anyone recreate the same environment with `pip install -r requirements.txt`. ScaleDojo's own backend uses exactly this file.
- -A venv isolates a project's installed packages from every other project and from the system Python.
- -`pip install <package>` adds a third-party package; `pip freeze` lists what is currently installed.
- -None of this applies inside the Forge Algorithm Lab itself - its sandbox is pre-configured and does not install or need packages - but it is essential knowledge for writing Python anywhere else.
Why is `with open("file.txt") as f:` preferred over calling `open()` and `.close()` manually?