6 Creating and Managing Python Virtual Environments
This chapter covers
- Why virtual environments matter (and what goes wrong without them)
- Creating a virtual environment with python3.13 -m venv
- Activating and deactivating on macOS
- Installing packages with pip
- Freezing and restoring dependencies with requirements.txt
When you are writing a Python program, you can save a lot of time and effort by using prewritten code, available as Python packages. But before you install any Python packages for your chatbot project, you need to understand virtual environments. This concept may seem tedious at first, but it is one of those foundational practices that separates clean, professional Python development from chaos. By the end of this chapter, you will be able to create isolated Python environments for any project, install packages safely, and share your exact setup with anyone---a skill you will use in every chapter that follows.
6.1 Why Virtual Environments Matter
Imagine you have three different projects on your computer: an AI chatbot, a web scraper, and a data analysis tool. Each project needs different Python packages---reusable bundles of code written by other developers that add new capabilities to your programs. A package (also called a library) might provide tools for making web requests, building user interfaces, or connecting to an AI model. You do not need to write everything from scratch; you install packages that other people have already built and tested.