How do you create a virtual environment in Python?

Using the 'venv' Module to Create a Python Virtual Environment

The optimal method to create a virtual environment in Python is through the built-in venv module. This way, you keep your system's Python enviroment uncluttered, with each project getting its own space where all dependencies are installed separately from one another.

To create a new virtual environment, you simply need to initiate the venv module followed by the name of your virtual environment as shown in this command:

python3 -m venv my_env

Replace 'my_env' with the name of the virtual environment you want to create.

After running this command, a directory named 'my_env' (or whichever name you specified) is created. This directory contains all the necessary executables to use the packages that a Python project would need.

But how do you use this virtual environment? Easy, you just activate it. Depending on your operating system the command to activate the virtual environment differs. On Unix or MacOS, the command is:

source my_env/bin/activate

And on Windows:

.\my_env\Scripts\activate

Once activated, your virtual environment has its own independent Python binary and can have its own independent set of installed Python packages in 'site-packages'. The name of the currently active virtual environment is usually indicated in your shell prompt to make it clear which environment is active. To deactivate the environment and return to your system's default Python interpreter, simply type 'deactivate'.

By using the venv module, you can avoid problems associated with project dependencies and ensure a smoother development process. It's a best practice to use virtual environments for your Python projects to isolate package installations and versions. This way, you don't have to worry about package conflicts and it makes it easier to share your project and its dependencies with others.

Remember, while there are other ways to create virtual environments in Python like virtualenv and pyenv, the built-in venv module is the most straightforward way to create them, especially if you're using Python 3.3 or later. It's always preferable to use in-built modules where possible to maximise compatibility and minimise additional dependencies.

Do you find this helpful?