Virtual Environment (venv) in Python
Learn how to create and manage isolated Python environments using the built-in venv module. Understand why virtual environments are important and how they prevent dependency conflicts.
Why Virtual Environments?
When working on multiple Python projects, each project may require different versions of the same package. For example: - Project A may require requests version 2.25 - Project B may require requests version 2.31 If you install everything globally, version conflicts can break your applications. A virtual environment creates an isolated Python environment for each project. Each environment has: - Its own Python interpreter - Its own installed packages - Its own pip This prevents dependency conflicts and keeps projects clean.
Creating a Virtual Environment
Python includes a built-in module called venv that allows you to create virtual environments easily.
Create a New Environment
Use the built-in venv module to create a new isolated environment.
What Gets Created?
After creating a virtual environment, the folder structure looks something like this:
Activating the Virtual Environment
After creating a virtual environment, you must activate it before installing packages.
Activate on macOS/Linux
Run the activation script using the source command.
Activate on Windows
Run the activation script from the Scripts directory.
Installing Packages Inside Virtual Environment
Once activated, any package you install using pip will be installed only inside this environment.
Install a Package
Install a package inside the activated environment.
Deactivating the Virtual Environment
When you are done working, you can deactivate the environment.
Deactivate Environment
Run the deactivate command to return to the global environment.
Best Practices with venv
Here are some important best practices: 1. Always create a virtual environment for each project. 2. Do not commit the venv folder to Git. 3. Add venv or myenv to your .gitignore file. 4. Use requirements.txt to track dependencies. 5. Activate the environment before installing packages. Virtual environments are considered a standard practice in professional Python development.