Setup a Python venv

| 2 minutes read

How and Why to Use venv in Python

As a frequent Python user, I often find myself writing scripts for various tasks—whether it’s solving Advent of Code challenges or analyzing data from a JSON file of my YouTube search history. During these projects, managing dependencies can quickly become cumbersome, especially when juggling multiple Python versions and package managers like pip, pip3, and pipx. With multiple versions of Python installed, it can be difficult to know which one is being used, or where libraries are being installed.

An effective way to manage this complexity is by using Python’s built-in venv (virtual environment). It allows you to create isolated environments for your projects, ensuring that dependencies are kept separate from your global Python setup.

Steps to Use venv

Here’s how you can create and activate a virtual environment:

# Navigate to your project directory
cd path/to/your/project
# Create a virtual environment with Python 3.12 (or your desired version)
python3.12 -m venv venv
# Activate the virtual environment
source venv/bin/activate
# Install the required libraries using pip
pip install <library_name>

This will install the necessary libraries locally within your venv environment. To keep track of these dependencies, you can create a requirements.txt file (which I highly recommend).

Simply run:

pip freeze > requirements.txt

Then, others can replicate your environment using:

pip install -r requirements.txt

Deactivating the Virtual Environment

When you’re done working in the virtual environment, you can deactivate it by running:

# Seems wrong, but works :D
deactivate

Why Use venv?

Using venv provides several advantages: • Isolation: Dependencies are kept within the virtual environment, preventing conflicts with your global Python installation. • Version Control: You can specify exactly which Python version you want to use for each project. • Portability: Sharing a requirements.txt ensures that others can recreate the same environment, making collaboration smoother.

In conclusion, venv is a simple yet powerful tool for managing Python project dependencies, and it helps keep your development environment clean and organized.

Enjoy coding with a clean, isolated environment!