Chapter 3
Isolated Environments and Packages
One Python, Many Projects
Every program you have written so far was built entirely from things Python already had. That is a real achievement, and it is also unusual. Most working Python programs lean on code somebody else wrote.
Code you did not write
Say you want your program to fetch a page from the internet. You could work out how to speak the protocol yourself, which is weeks of careful work, or you could use the code somebody has already written and tested for exactly that.
That second option is a package: a reusable bundle of Python code that you add to a project deliberately. Many packages come from other people; a team can package its own shared code too. Once a package is installed in an environment, programs using that environment can import it.
Fundamentals I told you packages were outside its
There is a catch, and the rest of this lesson is about it.
Two projects, one shelf
A package is not written once and finished. It gets fixed and extended, and each release gets a version number. Your program does not simply need “that package”; it needs a version whose behavior matches what you wrote.
The shell can run your program now, but programs that use this Python environment still reach the same collection of installed packages. Picture that as one shelf they all share.
Imagine a weather project written against version 2 of some package. A month later you start a travel project that needs version 3. Install version 3 on the shared shelf and the weather project may quietly stop working, because version 2 is simply not there anymore. Neither program is wrong. They made different promises at different times, and one shelf cannot keep both.
Give the boundary to the project
The useful answer is a small Python environment inside each project directory. The weather project gets its package versions. The travel project gets its own. Changing one does not rearrange the other.
That boundary is called a
We will call the directory .venv. The leading dot is a convention that says, “this supports the project; it is not one of the project’s source files.” Many editors recognize that name automatically.
Replaceable, not precious
A virtual environment can be large, contains machine-specific paths, and is made by tools. It is derived state, like a built copy of something whose recipe you still have. On the Python Land site it lives only in the working session and is excluded when the small project tree is saved or downloaded.
That is a feature. You should be able to delete or lose .venv and make an equivalent one again. The durable part is a short text file that states what the project needs. You will build that file later in the chapter.
What is a package?
Why give each project its own virtual environment?
Next you will make the boundary and watch the shell step inside it.