Setting Up A Virtual Environment

It is a fact that as we engage in various kinds of projects in Python, we'll come across dependencies. These dependencies are a general phrase in software engineering that refers to when one piece of software depends on another or, put, a set of other people's code that we can install and utilize instead of having to rewrite it ourselves. Having a virtual environment comes in handy when we come across these dependencies.

What Is a Virtual Environment?

A virtual environment is an aid that creates segregated python virtual environments for distinct projects to keep their dependencies separate. Most Python programmers utilize this as one of their most essential tools. It is a form of environment that contains Python executable files and additional files that identify it as such.

Benefits of Having a Virtual Environment

The primary benefit of having a virtual environment is, as I've said earlier, which is that virtual environments exist so that we can separate the dependencies of one project from the dependencies of another project, resulting in different versions of the same library being used. For example, we can work on Python projects that require different versions of Python simply by switching environments.

Python Versions of Python and associated pip packages can be decoupled and isolated using virtual environments. Thus, we can install various pip packages once we have created a virtual environment.

Setting up a Virtual Environment

Open a python folder (or create one if you haven't) using the source code editor on your device, and you can also use the command prompt if that's what is suitable.

Locate the terminal of the editor and type this on it:

python -m venv env folder's dir

Once we've done this, we'll see the virtual environment file inside the Python folder we created, indicating that we've successfully set up our virtual environment.

45.JPG

NOTE: You need to activate your virtual environment before you can start using it. To get this done, type the following on the terminal of your source code editor (note that your terminal should show the location of where your Python is installed);

If you use Windows:

env\Scripts\activate.bat

If you use Mac or Linux:

source env/bin/activate

Conclusion

This article talked about what a virtual environment is, its importance, and how to set it up on your source code editor. Creating a virtual environment is advantageous because, through it, you can install various python modules as you engage in different projects.