Virtual environments and packages
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
deactivatepython3 -m venv .venvcreates the environment in.venv.pip installadds a package to the active environment only.requirements.txtlists exact versions so someone else can runpip 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.