Skip to content

Virtual Environment in Python 3

Posted on:November 12, 2024 at 01:01 PM

Virtual Environment

In default python 3 is installed in our operating system, it use to run system apps. But, that python is too general to be used in our projects, we need python and it’s module / dependencies only used in that environment, that’s why we need virtual environment.

If we don’t use virtual environment, we will use the global module, which are sometimes the module version doesn’t match to our project module. It will occur errors.

With virtual environment we can use certain python and modules version without crashes with the global module because virtual environment is isolated.

As I know, there are two ways to use virtual environment in our project, with venv and uv.

I personally prefer to use uv. So here I will explain how to use uv.

Let’s say we have project directory todo-list-api and we want to add virtual environment with uv to that directory.

First, make sure you have installed uv using brew.

brew install uv

After uv is installed, go to the project directory and initialize the virtual environment

# in project directory (ex: todo-list-api)
uv venv

With that command, uv will create directory .venv and store all needed for virtual environment there. Basically we can change the directory name, but it’s common to use .venv for the virtual environment directory.

To activate the virtual environment

source ./venv/bin/activate

After that to check if the virtual environment is active

which python

If the python is displayed from the project directory it means the virtual environment is active.

Always make sure the virtual environment before add / remove module, and I recommend to activate the virtual environment again after you install module.

To deactivate the virtual environment in the directory

deactivate

With uv you don’t need to install pip manually because pip is already included in uv. You can use pip with uv pip, for example

uv pip freeze > requirements.txt

That command will generate module from the environment and create requirements.txt to install it again if you store the project in repository (github / gitlab / somewhere). And to install the modules you can do it with uv pip install -r requirements.txt