Chapter 3, Environment
pyenv: multiple versions of Python on the same machine
When two projects require different versions, switching the system Python is not an option. pyenv solves this by compiling isolated versions in your user folder.
Code for this chapter: ambiente/cap03_pyenv.py
The problem that pyenv solves
An old project runs on Python 3.12, a new one asks for 3.14, and the library you are testing only works on 3.13. pyenv installs all of them side by side and chooses the right version based on the folder you are in, using a file .python-version.
brew install pyenv
xcode-select --install
If the Apple command line tools are already installed, the second command will notify you and do nothing.
Activate pyenv in the shell
On macOS and Linux, pyenv needs to intercept the command python. Add these lines to ~/.zshrc (zsh) or to ~/.bashrc (bash) and open a new terminal:
export PYENV_ROOT="$HOME/.pyenv"
[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
Install and choose versions
pyenv install --list | grep -E "^\s*3\.1[234]\."
pyenv install 3.13
pyenv versions
pyenv global 3.13
Inside a project's folder, pyenv local writes the file .python-version, which should go to Git:
cd meu-projeto
pyenv local 3.12
python --version
pyenv chooses the active version following a priority order:
| Priority | Mechanism | How to set |
|---|---|---|
| 1 (highest) | Current terminal session | pyenv shell 3.14 |
| 2 | Project folder | pyenv local 3.12 |
| 3 (lowest) | User default | pyenv global 3.13 |
To ensure in the code itself that the version is as expected, the script below fails early and with a clear message:
import sys
assert sys.version_info >= (3, 12), "Este livro exige Python 3.12 ou superior"
print("versão ok")
versão ok
The cost of compiling
pyenv compiles each version from source code, which takes a few minutes and depends on the installed development libraries. uv, which I introduce in chapter 7, downloads ready binaries and installs the same version in seconds. I use pyenv when I need a specific build and uv for everything else.