Setting Up a Local Environment Using Pyenv and venv

Overview

This article documents how to set up a Python environment for development on a Mac local environment.
In this case, we will use two systems to manage different versions of Python and virtual environments:

  • pyenv
    • Used to handle multiple versions of Python.
  • venv
    • Used to separate environments for each project.

For explanations on the differences and the necessity of each, this article is a helpful reference.

Installing Python

First, install Pyenv on your local environment to use a specific version of Python.

Install pyenv.

1
brew install pyenv

Check the installed version of pyenv.

1
2
pyenv --version
pyenv 2.3.35

Add settings to zsh.

1
2
3
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc    
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.zshrc

Reload .zshrc.

1
source ~/.zshrc

Display a list of installable Python versions.

1
pyenv install --list

Install the specified version.

1
pyenv install 3.11.7

Use the specified Python version in your project folder.

1
2
3
cd <created project folder>
pyenv local 3.11.7
pyenv versions

If global, it will be applied to the entire system.

1
pyenv global 3.11.7

Check the version of Python being executed.

1
python -V

Creating a Virtual Environment with venv

Create a virtual environment in the project directory.

1
2
# python -m venv <virtual environment name>
python -m venv venv

Activate the virtual environment.

1
source venv/bin/activate

To deactivate, execute the following command.

1
deactivate

How to Update a venv

If you need to refresh dependencies, activate the virtual environment and run the following. When using requirements.txt, update the file first and then reinstall.

1
2
3
source venv/bin/activate
pip install --upgrade pip
pip install -U -r requirements.txt

When upgrading Python to a new minor version, install the new version with pyenv, recreate the virtual environment, and reinstall dependencies to avoid mismatches.

1
2
3
4
5
6
pyenv install 3.12.2
pyenv local 3.12.2
rm -rf venv
python -m venv venv
source venv/bin/activate
pip install -U -r requirements.txt

How to Delete a venv

When the virtual environment is no longer needed, delete the directory. Confirm you are in the correct working directory before running the command.

1
rm -rf venv

This completes the setup of the local environment.