It looked like this.
#!/usr/bin/env python3 import numpy as npWe were able to run this script from inside our active environment with no problems because our environment’s Python instance was able to access our project’s local site packages.
What happens if we run the same script from outside our project’s virtual environment?% tests/imports-test.
py # Look, no active environmentTraceback (most recent call last): File "tests/imports-test.
py", line 3, in <module> import numpy as npModuleNotFoundError: No module named 'numpy' Yep, we get an error — as we should.
If we didn’t, it would mean we were able to access our project’s local site packages from outside our project, defeating the entire purpose of having a virtual environment.
The fact that we get an error is proof our project is completely isolated from the rest of our system.
The Directory Tree of an EnvironmentOne thing that helps me keep all of this information organised in my head is having a clear picture of what an environment’s directory tree looks like.
test-project/venv/ # Our environment's root directory├── bin│ ├── activate # Scripts to activate│ ├── activate.
csh # our project's│ ├── activate.
fish # virtual environment.
│ ├── easy_install│ ├── easy_install-3.
7│ ├── pip│ ├── pip3│ ├── pip3.
7│ ├── python -> /usr/local/bin/python # Symlinks to system-wide│ └── python3 -> python3.
7 # Python instances.
├── include├── lib│ └── python3.
7│ └── site-packages # Stores local site packages└── pyvenv.
cfgDante and Virgil return to the mortal realm — Canto XXXIV.
Illustration by Gustave Doré.
Further ReadingIf your curiosity hasn’t been satisfied and you still want to know more about virtual environments, I highly recommend Real Python’s terrific primer on virtual environments.
And if you find yourself in thrall to the remarkable illustrations of Gustave Doré, I highly recommend reading Dante’s Inferno.
Other than that, that about does it for us.
If you’d like to stay up to date with my data science-y postings, feel free to follow me on twitter.
Cheers, and happy reading.