Use virtual environments with Anaconda

Anaconda (conda) can create a python bubble for you with no preinstalled packages. You can create a Python virtual environment for each of your projects to isolate them and only install the required packages.

When we distribute our code, we should specify the list of referenced Python packages including their versions in the requirements.txt file. This enables any other developer ( and the Docker container build process ) to install the appropriate packages and be able to successfully run our application.

When you install packages with pip, those packages are global, every project can see them. When we execute the pip freeze > requirements.txt command, all installed packages will show up in the requirements.txt file, not just the short list needed for the particular application.

When you execute your application, Python will prompt you to install the referenced packages. The resulting list is usually much shorter, than the long list of globally installed packages.

Install Anaconda

Download the installer from

Create your first virtual environment

To create an environment with only generic packages installed execute the command:

conda create -n MY_ENVIRONMENT_NAME python=3.10
# At the time of writing python version 3.10
# is the latest for Anaconda packages

To create a new environment based on a requirements.txt file:

conda env create -f=requirements.txt -n MY_ENVIRONMENT_NAME

To create a new environment based on an environment.yml file:

conda env create -f=environment.yml

Working with virtual environments

List the Python virtual environments. The asterisk (*) shows to current environment.

conda env list

Activate an environment

conda activate MY_ENVIRONMENT_NAME

Delete an Anaconda environment

conda deactivate
conda env remove -n MY_ENVIRONMENT_NAME

Generate the dependency list for you project

Generate a standard text file with the list of packages and their versions installed in the current Python environment. This enables the Docker build or any developer to reproduce the same Python environment you have on your developer workstation.

pip freeze > requirements.txt

Leave a comment

Your email address will not be published. Required fields are marked *