The cart is empty

Developing software in Python often involves using various libraries and packages that may be specific to a particular project. To ensure that our application will work consistently across different development environments, it's important to maintain control over the versions of the used libraries. This is where virtual environments come into play, allowing us to isolate dependencies for each project. In this article, we will explore what virtual environments are and how to effectively work with them.

What are Virtual Environments?

Virtual environments in Python are isolated directories that contain everything needed to run and work on your project – Python interpreter, libraries, and scripts. Thanks to this isolation, you can work on multiple projects requiring different versions of the same libraries on a single machine without them interfering with each other.

How to Create a Virtual Environment?

To create a virtual environment, you first need to have Python installed. Most Python distributions already include the venv tool, which is used to create virtual environments. To create a virtual environment in the current directory, you can use the following command:

python3 -m venv environment_name

Activating a Virtual Environment

After creating a virtual environment, you need to activate it to work within it. Activation varies depending on the operating system:

  • On Windows, use the command:
    environment_name\Scripts\activate.bat
    ​
  • On Unix or MacOS, use the command:
    source environment_name/bin/activate
    ​

After activation, you should see the name of the virtual environment in the command prompt, indicating that all subsequent python and pip commands will use the interpreter and libraries isolated within this environment.

Installing Libraries into the Virtual Environment

Installing libraries is done using the pip tool, just as usual. Thanks to the activated virtual environment, all libraries will be installed isolated within it, rather than in the global Python environment. You can install a library using the command:

pip install library_name

Deactivating a Virtual Environment

Once you've finished working within a virtual environment, it's a good practice to deactivate it to return to the global Python environment. This can be done with a simple command:

deactivate

Virtual environments are a crucial tool for efficient software development in Python. They allow you to isolate project dependencies and simplify library version management. With the help of the venv tool and the pip package manager, using virtual environments is easy and beneficial for every developer.