Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited 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 theOfficial python documentation,Virtualenv was meant for python2 but python2 is no longer supported by thepython software foundation.
And though, you can still make a virtual environment for your python3 projects with theVirtualenv module,venv is the most recommended way in these days.

Creating a virtual environment is pretty simple.

Steps : -

  1. Make sureensurepip 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 modeExit fullscreen mode

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

python3-m venv ./.venv
Enter fullscreen modeExit 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, ormyenv, 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

Thebin (orScripts on Windows) is the subdirectory containing a copy or 'symbolic link' of the Python binaries.

Inside the lib directory, there'll be apython3.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.

PlatformShellCommand to activate virtual environment
POSIXbash/zshsource ./.venv/bin/activate
POSIXfishsource ./.venv/bin/activate.fish
POSIXcsh/tcshsource ./.venv/bin/activate.csh
Windowscmd.exe.\.venv\Scripts\activate.bat
WindowsPowerShell.\.venv\Scripts\Activate.ps1

Wow! You made it!!🎊 You initialized your python project with avenv 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, theimport 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 thevenv?

In windows machine, run -

.\.venv\Scripts\pip3install<name-of-the-module>
Enter fullscreen modeExit fullscreen mode

In a Linux/MacOS/BSD machine, run -

./.venv/bin/pip3install <name-of-the-module>
Enter fullscreen modeExit 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 modeExit 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/pip3install-r requirements.txt
Enter fullscreen modeExit 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 orGitHub :)

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

Top comments(8)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jsporna profile image
Jakub Spórna
  • Location
    Siemianowice Śląskie, Silesia, Poland
  • Work
    Cloud Architect, DevOps Engineer at self-employed
  • Joined

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".

CollapseExpand
 
ddebajyati profile image
Debajyati Dey
Web Developer, Linux enthusiast, always eager to learn new technologies
  • Location
    West Bengal, India
  • Education
    Maulana Abul Kalam Azad University of Technology, W.B.
  • Pronouns
    He/Him
  • Joined

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

CollapseExpand
 
swapnoneel123 profile image
Swapnoneel Saha
Building cool things using Python and a Freelance Developer & UI/UX Designer

Crisp and informative!! Nice work Debajyati!!

CollapseExpand
 
ddebajyati profile image
Debajyati Dey
Web Developer, Linux enthusiast, always eager to learn new technologies
  • Location
    West Bengal, India
  • Education
    Maulana Abul Kalam Azad University of Technology, W.B.
  • Pronouns
    He/Him
  • Joined

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

CollapseExpand
 
sammaji profile image
Samyabrata Maji
Software engineer
  • Email
  • Location
    Kolkata, West Bengal
  • Education
    Maulana Abul Kalam Azad University of Technology, West Bengal
  • Joined

Great article!!

CollapseExpand
 
ddebajyati profile image
Debajyati Dey
Web Developer, Linux enthusiast, always eager to learn new technologies
  • Location
    West Bengal, India
  • Education
    Maulana Abul Kalam Azad University of Technology, W.B.
  • Pronouns
    He/Him
  • Joined

Thanks samya!

CollapseExpand
 
subhro profile image
Subhradip Sinha
Python lover | Curious programmer
  • Joined

Awesomely done ✅ really appreciate your effort 👍

CollapseExpand
 
ddebajyati profile image
Debajyati Dey
Web Developer, Linux enthusiast, always eager to learn new technologies
  • Location
    West Bengal, India
  • Education
    Maulana Abul Kalam Azad University of Technology, W.B.
  • Pronouns
    He/Him
  • Joined

Thank you Subhra! 🙌😄

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Web Developer, Linux enthusiast, always eager to learn new technologies
  • Location
    West Bengal, India
  • Education
    Maulana Abul Kalam Azad University of Technology, W.B.
  • Pronouns
    He/Him
  • Joined

More fromDebajyati Dey

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp