I have been primarily focusing on Python recently (if that wasn’t obvious already) and I’ve been having some trouble understanding why virtual environments exist. I’ve never used one for other languages, so why use one for Python?

Python has interesting ways of storing/managing libraries and packages. Packages can be stored in your system using easy_install or pip (see differences between the two here). Python projects that require these packages/dependencies can then pull them from wherever they were stored in your system. This is great for system packages, meaning packages that are universally used by Python, or part of the normal Python setup. However, this can get tricky for site-packages. The latter refers to any project-specific dependencies. So what if you have two projects that both require the same package but different versions of the package? Your system will only store one version of the package, but if you utilize a virtual environment (venv) and install those dependencies within the venv, each project can have their specific dependencies instead of pulling from the system’s data.

Python3 has a venv feature built in, and once you’re inside your designated project folder (before creating the rest of your project files), you can run this command:

python -m venv venv

where the second ‘venv’ is what you want to call your venv. So, if I wanted to name my venv ‘cool_venv,’ then the command would be:

python -m venv cool_venv

If you view what’s in your project folder, you’ll see a folder for your venv. Next, you will need to activate it by running:

. ./cool_venv/bin/activate

again, where ‘cool_venv’ is where you put the name of your venv. Now you can start building your project and installing packages.

#software-engineering #web-development #python #virtualenv

Python Virtual Environments
1.20 GEEK