Skip to Content
Course content

161: Virtual Environments with venv

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen too many junior devs blow up their system Python installation by installing every package they find on PyPI globally. It starts out fine, but eventually, you'll hit a wall where Project A needs version 1.0 of a library and Project B needs version 2.0. You can't have both globally, and suddenly you're spending your afternoon debugging installation errors instead of writing code. That's why we use virtual environments.

Avoiding the Global Package Mess

For this lesson, we're going to build a simple Crypto Price Tracker. It's a tiny script that hits a public API to tell us the current price of Bitcoin. To do this, we need the requests library. Instead of installing requests globally—where it'll just sit there forever taking up space and potentially clashing with other tools—we're going to carve out a dedicated sandbox for this project using venv.

# Create a directory for our project
mkdir crypto_tracker
cd crypto_tracker

# Create the virtual environment
python -m venv .venv

I call the folder .venv. The leading dot makes it hidden on macOS and Linux, which keeps my project root clean. The python -m venv command essentially tells Python to create a lightweight copy of the Python binary and a private site-packages folder right inside that directory.

The "Wait, where did my package go?" moment

Now, here is where I usually trip up when I'm rushing. Watch what I do. I'm going to try to install my dependency immediately.

pip install requests
python main.py

Wait. I just realized I forgot to activate the environment. I ran pip install requests, but because I hadn't activated .venv, I just installed requests into my global Python environment. If I now activate the environment and try to run my code, it'll crash with a ModuleNotFoundError because the virtual environment is empty—which is exactly what it's supposed to be!

Let's fix this. First, I'll activate the environment. Depending on your OS, the command differs slightly:

# On macOS/Linux:
source .venv/bin/activate

# On Windows:
.venv\Scripts\activate

Once you see (.venv) appear in your terminal prompt, you're officially inside the sandbox. Now, I'll install the library inside the environment where it belongs.

pip install requests

Actually getting the code to run

Now that our environment is locked and loaded, let's write the script. Create a file called main.py and drop this in:

import requests

def get_bitcoin_price():
    url = "https://api.coindesk.com/v1/bpi/currentprice.json"
    response = requests.get(url)
    data = response.json()
    price = data["bpi"]["USD"]["rate"]
    print(f"The current price of Bitcoin is ${price}")

if __name__ == "__main__":
    get_bitcoin_price()

Run it with python main.py. It works perfectly. The beauty here is that if I start another project tomorrow that requires an ancient version of requests, I just create a new .venv for that project, and this Crypto Tracker remains completely untouched and functional.

Keeping the repository clean

One last piece of professional advice: never, ever commit your .venv folder to version control. It's huge, and it's specific to your machine's operating system; it won't work for anyone else who clones your code. Instead, we use a requirements.txt file.

pip freeze > requirements.txt

This creates a simple text file listing requests and its version. When someone else wants to run your project, they'll create their own venv and run pip install -r requirements.txt. Clean, professional, and predictable.




📋 Practical Task

Exercise: Building a Weather Snapshot Environment

Your goal is to create a completely isolated environment for a new project called weather_snapshot. Follow these requirements strictly to ensure your environment is configured correctly:

  • Create a project folder named weather_snapshot.
  • Initialize a virtual environment inside that folder named .env.
  • Activate the environment.
  • Install the pyowm library (the Python OpenWeatherMap wrapper) using pip.
  • Create a requirements.txt file that captures the installation.
  • Verify that pyowm is installed only in the virtual environment and not in your global Python space (you can check this by running pip list while the environment is deactivated).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.