appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Virtual environments and packages

Lesson 4 of 510 minIntermediate

Keep each project’s dependencies separate and reproducible.

Different projects need different versions of libraries. A virtual environment is a private folder with its own Python packages, so projects do not interfere with each other or with the system.

python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install requests
pip freeze > requirements.txt
deactivate
  • python3 -m venv .venv creates the environment in .venv.
  • pip install adds a package to the active environment only.
  • requirements.txt lists exact versions so someone else can run pip install -r requirements.txt.

Your own modules

Any .py file is a module. A folder of modules is a package. Use import to share code between files, and guard the entry point so importing does not run it.

# utils.py
def slugify(s):
    return s.lower().replace(" ", "-")

# main.py
from utils import slugify

if __name__ == "__main__":
    print(slugify("Hello World"))

CarefulNever commit the .venv folder to Git. Add it to .gitignore and share requirements.txt instead. Install only packages you trust: a malicious package runs code on your machine.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What problem does a virtual environment solve?
2. What is if __name__ == "__main__" for?
Hintpython3 -m venv ...

Key terms