DEV Community

Cover image for Pythonic Isolation: Virtual Environments
Debajyati Dey
Debajyati Dey

Posted on • Updated on

Pythonic Isolation: Virtual Environments

What are virtual environments?

Virtual environments in Python are isolated, self-contained spaces that allow you to separate dependencies for different projects.

Why even I would need a virtual environment for my project?

Suppose, you need a feature from a module that aligns/better supports your project requirements but was present in some earlier versions of that module.

A virtual environment allow us to separate our different project environments from themselves and also from from the global python environment. This prevents conflicts between libraries required by different projects.

Not only that, Virtual Environments can also help us to ensure that we or whoever uses our project, uses the exact same version of the libraries as dependencies which we used to build our projects.

So let's dive in and see how we can initialize our project with a virtual environment.

Creating a Virtual Environment

A virtual environment is created two ways, with - 1. venv module or, 2. Virtualenv module.
According to the Official python documentation, Virtualenv was meant for python2 but python2 is no longer supported by the python software foundation.
And though, you can still make a virtual environment for your python3 projects with the Virtualenv module, venv is the most recommended way in these days.

Creating a virtual environment is pretty simple.

Steps : -

  1. Make sure ensurepip is preinstalled.
  2. Navigate to your project directory.
  3. Open in terminal.
  4. Run this command shown below.
python3 -m venv <path-to-your-venv-directory>
Enter fullscreen mode Exit fullscreen mode

Or if you're currently inside the project directory, just do this-

python3 -m venv ./.venv
Enter fullscreen mode Exit fullscreen mode

Now you may be thinking what is this .venv thing?🤔

Well, .venv is just a naming convention for the target environment initializer directory.
You can also choose any other name for your directory, such as - .env, or myenv, etc.
WAIT! WAIT!! WAIT!!!
But from my experiences, for once in the last 2 years, naming the target directory as .env or any other name rather than .venv was causing some unexpected errors to happen. So don't think much and take my opinion. Always name the directory .venv & remain less prone to errors.
Maybe it was just a one time bug. You never know.

Okay, but what's inside this .venv folder 🧐

  1. A pyvenv.cfg file with a home key pointing to the Python installation from which the command was run.
  2. 3 subdirectories.
    • include,
    • bin (Scripts in Windows) &
    • lib

The bin (or Scripts on Windows) is the subdirectory containing a copy or 'symbolic link' of the Python binaries.

Inside the lib directory, there'll be a python3.x/site-packages/ directory that will initially be empty but, when you'll try to install a package inside your virtual environment it will be installed here.

Activating the virtual environment 🚀

Up until now we've just created the target folder(.venv) for our
Virtual Environments. You won't see any difference unless you activate them.
Virtual Environments are activated differently in Windows environments and POSIX compliant (Linux, MacOS, BSD and any other unix based OS) environments.

Let's see how can activate our virtual environment.
Take a Look at the table below. Run the command corresponding to your platform and shell.

Platform Shell Command to activate virtual environment
POSIX bash/zsh source ./.venv/bin/activate
POSIX fish source ./.venv/bin/activate.fish
POSIX csh/tcsh source ./.venv/bin/activate.csh
Windows cmd.exe .\.venv\Scripts\activate.bat
Windows PowerShell .\.venv\Scripts\Activate.ps1

Wow! You made it!!🎊 You initialized your python project with a venv for the first time! Bravo! 👏

An important Note 👽

Virtual Environments are shell dependent. By that What I mean is that whenever you activate a venv that is only activated for the shell instance. In any new shell instance, you won't get access to the virtual environment.
If you have opened your code editor through an inactive shell instance, the import statements will point towards the library modules installed in the global environment if any. This can cause many unexpected problems to occur.
So, be cautious about that.

How to install libraries in the venv?

In windows machine, run -

.\.venv\Scripts\pip3 install <name-of-the-module>
Enter fullscreen mode Exit fullscreen mode

In a Linux/MacOS/BSD machine, run -

./.venv/bin/pip3 install <name-of-the-module>
Enter fullscreen mode Exit fullscreen mode

Common questions regarding a virtual environment

Should I push the .venv folder also when hosting my project to GitHub?

No! Virtual Environments should never be pushed to your github repo.

Then how would I ensure that someone trying out my project will be installing the dependencies of the exact same versions?

Pip offers us a very nice way to ensure that.😎
Run -

./.venv/bin/pip3 freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

This command will create a text file named requirements.txt and record your environment's current package list into the file.

Add your .venv folder to the .gitignore file & push requirements.txt in your repository.

When anyone will need to install the dependencies, the person will run -

./.venv/bin/pip3 install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

and all the dependencies will be installed one-by-one after inspection from the list.

Conclusion

If you found this article helpful, if this blog added some value to your time and energy, please show some love by giving the article some likes and share it with your friends.

Feel free to connect with me at - Twitter, LinkedIn or GitHub :)

Happy Coding 🧑🏽‍💻👩🏽‍💻! Have a nice day ahead! 🚀

Top comments (8)

Collapse
 
jsporna profile image
Jakub Spórna

Proposition to use .env name for virtualenv folder is IMHO catastrophe. That name is "reserved" for config file where are kept environment variables with values for local environment. I bet it was the root cause of "causing some unexpected errors".

Collapse
 
ddebajyati profile image
Debajyati Dey

Oh! didn't know about that! Thanks for the insight!

Collapse
 
swapnoneel123 profile image
Swapnoneel Saha

Crisp and informative!! Nice work Debajyati!!

Collapse
 
ddebajyati profile image
Debajyati Dey

Thanks Swapnoneel for your kind words.
Glad you found it useful.

Collapse
 
sammaji profile image
Samyabrata Maji

Great article!!

Collapse
 
ddebajyati profile image
Debajyati Dey

Thanks samya!

Collapse
 
subhro profile image
Subhradip Sinha

Awesomely done ✅ really appreciate your effort 👍

Collapse
 
ddebajyati profile image
Debajyati Dey

Thank you Subhra! 🙌😄