You might have heard about virtual machines (VMs) before. A virtual machine allows you to run a different operating system on your current operating system. For example, you could use a VM to run Linux on a Mac.
You can create a VM with programs such as virtualbox. The VM is a separate environment that is self-sufficient and doesn't need to interact much with the main OS of your computer.
Python Virtual Environments
Python Virtual environments are a similar concept, only that they don't box up a complete operating system, but instead just the following:
- Python: An installation of Python
- Packages: Python modules and packages
Instead of creating a virtual machine, you create a virtual environment specifically for your Python:
If you keep your Python project inside a virtual environment, then you're keeping it and all the packages for that specific project safe from other environments. You also keep the rest of your computer safe from whatever goes on inside your terrarium, ahem, virtual environment.
Virtual Environment Example
Your computer needs to create a folder to store your project-specific Python as well as all the external packages you'll install for the project. On macOS, the contents of the virtual environment folder look something like this:
.
├── bin
│ ├── Activate.ps1
│ ├── activate
│ ├── activate.csh
│ ├── activate.fish
│ ├── dmypy
│ ├── easy_install
│ ├── easy_install-3.8
│ ├── mypy
│ ├── mypyc
│ ├── pip
│ ├── pip3
│ ├── pip3.8
│ ├── python -> /Users/martin/.pyenv/versions/3.8.5/bin/python
│ ├── python3 -> python
│ ├── stubgen
│ └── stubtest
├── include
├── lib
│ └── python3.8
│ └── site-packages
│ ├── 8c8c5116bc4884237d33__mypyc.cpython-38-darwin.so
│ ├── __pycache__
│ │ ├── easy_install.cpython-38.pyc
│ │ ├── mypy_extensions.cpython-38.pyc
│ │ └── typing_extensions.cpython-38.pyc
│ ├── easy_install.py
│ ├── mypy
--- snip ---
On Windows, the folder structure is similar but not quite the same. For now, the differences between the folder structures on the different operating systems don't matter.
What you can see in the tree structure above is just a small part of all the files and folders that make up such a virtual environment. If you're curious, you can look at the full contents of an example virtual environment.
Whether you ventured bravely to follow the link or not, you'll see that this folder structure is huge. That might seem daunting, and it would be if you had to build it yourself.
But instead, Python comes bundled with a command that creates all of that for you. You'll get to know it in the next lesson.
Summary: Python Virtual Environments
- Using virtual environments makes software development safer and more reproducible by keeping your Python interpreter together with project-relevant external packages in a dedicated folder.
- Starting to use them early on can be a huge time-saver. In the next lesson, you'll create your first virtual environment.