What is a virtual environment?
A virtual environment allows having a Python interpreter, packages and dependencies separately for a particular project or type of project. The packages installed in a venv are not installed globally but within the venv. By using virtual environments, it is possible to have mutually exclusive dependencies for different projects.
This guide is to quickly set up a virtual environment and complete explanation is out of the scope. In case you want to know more about virtual environments, refer to the Python Docs.
Example Use Cases
- To work with an older version of packages for a project
- To test a new dependency without disturbing old dependencies
- Build independent applications
In case you want to quickly create a virtual environment, you can run the following
python -m pip install --upgrade pip python -m pip install virtualenv python -m venv .venv # Windows .\.venv\Scripts\activate # Linux / Mac source .venv/Scripts/activate deactivate
Setting up a virtual environment
Note: For Linux users, you may want to use python3 instead of python
A. Upgrade pip
Before we begin, we need to ensure pip is upgraded.
python -m pip install --upgrade pip
B. Install virtualenv
We recommend installing for all users. However, if you don’t have administrator access or want to install only for the current user, you can add
python -m pip install virtualenv
C. Create an environment
Create an environment with the name .venv. You can create with the name of your choice. Adding a . before name keeps the file hidden.
python -m venv .venv
D. Activating the environment
For Windows users:
For Linux/ Mac users:
Once the virtual environment is activated, you can install your dependencies and run the application within the environment. When the environment is activated, you will see the name of the environment in front of your shell path:
E. Deactivate the Environment
In case you want to leave the environment or switch to a different environment, you can deactivate the current environment. The code is same for Windows as well as Linux/ Mac users.