This is going to seem weird, but I have seen "virtual environments" flying around since I started coding in 2022. Yet, I only just got the hang of them. For the longest time, they looked like some overly complex sorcery, and I would shy away every time someone mentioned them.
Fast forward to now, I am sitting here wondering how I have been surviving without them all this time.
Do not get me wrong, I had used virtual environments before. I knew how to spin one up when following tutorials, but it was always just one of those "do this because they said so" moments. I never really understood the power they wielded. But recently? Oh boy, things changed! I finally hacked how powerful they can be when properly integrated into a project, and now I cannot imagine coding without them.
So, here is how I have been rolling with virtual environments lately.
What Even Is a Virtual Environment?
If you are like how I used to be, you might have nodded along when people talked about virtual environments without actually knowing what they were. A virtual environment is basically a self-contained workspace where you can install project-specific dependencies without messing up your system-wide Python setup.
Think of it like a bubble for your project, everything it needs stays inside, away from global Python, keeping things clean and conflict-free. No more worrying about breaking other projects because some library decided to update itself to an incompatible version.
How To Setup Virtual Environments
1. Create a virtual environment
python -m venv my_env
This creates a new directory my_env
, which holds all the virtual environment goodies.
2. Activate it
- On Windows:
my_env\Scripts\activate
- On macOS/Linux:
source my_env/bin/activate
Once activated, your terminal will show (my_env)
, meaning you are now inside the isolated environment.
3. Install Dependencies
pip install requests flask
Boom! These packages are now installed only inside my_env
, not system-wide.
4. Deactivate When Done
deactivate
This takes you back to normal, global Python.
Why You Should Use Virtual Environments
- No More "It Works on My Machine" Nightmares - With a virtual environment, dependencies are locked to specific versions, so no more "why does it work for you but not for me?"
- Easy Project Switching - One can now hop between projects without dependency conflicts.
-
Better Collaboration - When sharing code, others can recreate exact environment using a
requirements.txt
file:
pip install -r requirements.txt
Now that I have finally embraced virtual environments, I cannot believe I was coding without them for so long. If you are like I was, seeing people talk about them but never really using them, trust me, it is worth the 5 minutes to set up. Your projects (and future self) will thank you!