Virtual Environment and Dependency Managers#

Learning Environments#

  • Understand the basics and importance of virtual environments and dependency management in Python

  • Explain why external libraries are used in Python projects

  • Create and manage virtual environments to isolate project dependencies

  • Install and manage dependencies using pip and requirements.txt

  • Activate and deactivate virtual environments to manage different project settings

This session will guide you through the basics of virtual environments and dependency management in Python.

Understanding the Basics#

Why Use External Libraries?#

Most Python projects require external libraries, known as third-party packages or dependencies, like matplotlib. These libraries provide specific functionalities, and sometimes, specific versions are needed for your project.

Dependency Management#

A dependency manager like pip allows you to specify and manage versions of dependencies required for your projects. It handles the installation and updates of these dependencies.

Virtual Environments#

Using a virtual environment (venv in Python) helps isolate and manage project-specific dependencies. This isolation simplifies development, testing, and collaboration across different projects and environments.

Key Steps and Commands#

Creating a Virtual Environment#

  • Open your terminal or command prompt.

  • Navigate to your project directory.

  • Create a virtual environment with: python3 -m venv myenv (replace myenv with your preferred environment name).

Activating the Virtual Environment#

  • On MacOS/Linux, activate with: source myenv/bin/activate

  • On Windows, activate with: source myenv/Scripts/activate

  • Your command prompt will show the environment name in brackets once activated.

  • Remember, if reactivating later, navigate to your project directory first.

Installing Dependencies#

  • Install a library, e.g., matplotlib, by running: python3 -m pip install matplotlib

  • For a specific version, use: python3 -m pip install matplotlib==3.7.0

  • To view installed dependencies: python3 -m pip list

  • To remove a dependency: python3 -m pip uninstall package-name

Managing Dependencies with requirements.txt#

  • Generate a requirements.txt file: python3 -m pip freeze > requirements.txt

  • This file can be used by others to replicate your environment using: python3 -m pip install -r requirements.txt

  • Update and maintain this file regularly, especially after changes to your environment.

Deactivating the Virtual Environment#

  • Simply run deactivate to exit your virtual environment.

  • The environment name will disappear from your command prompt.

Adapted Content From: Intermediate Research Software Development, The Carpentries Incubator (CC-BY 4.0)

Summary Quiz#