Member-only story

How to create virtual environments with venv and conda in Python

Learn to build a modern Python development

Lynn G. Kwong
7 min readJan 4, 2022

Virtual environments are very commonly used in modern Python development because they can provide isolated environments for running Python code. You can create different virtual environments for different projects, or even for different versions of the same project. The libraries installed in one environment are isolated from those of the system and also those of any other project. Moreover, you can install different Python versions in the environments. In this article, the two most common methods, namely venv and conda will be introduced. You will learn how to create and manage virtual environments from simple but useful code snippets.

Image by Mohamed_hassan (Online Meeting Virtual) from Pixabay

How to use venv to create virtual environments in Python?

The first tool is venv, which is a built-in and lightweight module for creating virtual environments in Python. To proceed with the code examples, you should have a modern version of Python installed, preferably newer than Python3.8. With the latest version of Python, you don’t need to install the venv library by yourself. However, since many operating systems don’t have the latest Python installed, you would need to install venv by yourself. In case you have such problems you need to run the following commands (on Linux).

$ sudo apt-get install python3-venv

Normally we should not change the default version of Python of the system because many system libraries depend on it. Later you will see how to create virtual environments with different versions of Python with conda, which is my favorite tool and is highly recommended.

To create a virtual environment with venv, simply run:

$ python3 -m venv .venv

For older systems, python defaults to python2. Depending on your operating system and the version of Python installed, you may be able to use python directly rather than python3. Anyway, python3 is the safe way to go.

With venv, the folder of the virtual environment is normally created inside the project folder. However, you can put it in any place you like. The major advantage of venv is that it is built-in and super lightweight and is thus suitable for…

--

--

Lynn G. Kwong
Lynn G. Kwong

Written by Lynn G. Kwong

I’m a Software Developer (https://youtube.com/@kwonglynn) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.

Responses (1)

Write a response