Managing Python Versions With pyenv Without Breaking Your System Python

The distribution ships Python for its own tooling, not for your projects. The day you run sudo pip install into it, or apt upgrades it under a project pinned to the old minor, something you did not write stops working.

I have cleaned up enough broken laptops and CI runners to have a rule I never break: leave the system interpreter alone. On Ubuntu, apt owns /usr/bin/python3, and half the desktop and server tooling depends on the exact version it installed. On macOS the Apple-supplied Python is worse still, changing under you between OS releases. pyenv gives every project its own interpreter, built from source and switched per directory, without touching either. Here is the setup I put on every new machine.

Who this is for

  • The developer whose python points at a distro interpreter and who has been told, correctly, never to sudo pip into it.
  • The team lead standardising machines where one repo needs 3.12 and another needs 3.13, on the same box, with no drama.
  • Anyone who has hit ModuleNotFoundError: No module named '_ctypes' or a missing ssl module after building Python and does not know why.

Why the system Python is off-limits

On a Debian-family system, /usr/bin/python3 is a package like any other, and packages depend on it. apt resolves those dependencies against the version it installed. Run sudo pip install into that interpreter and you are now editing files a package manager believes it owns; the next upgrade can overwrite or conflict with them, and unpicking it is a bad afternoon. The fix is not discipline about which flags you pass to pip. The fix is to never point project work at that interpreter at all. pyenv does this by building its own Python versions under your home directory and putting them ahead of the system one on PATH, only for your shell.

Free · 4 minutes

Is your engineering team shipping safely, or quietly accumulating risk?

Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.

Install pyenv and the build dependencies people skip

pyenv compiles CPython from source, so the compile has to find the headers for the optional modules. Miss libssl-dev and you get a Python with no working ssl; miss libffi-dev and _ctypes fails to build. The install still succeeds, and the breakage only surfaces later when something imports the missing module. Install the full set first. This is the list from the pyenv wiki’s suggested build environment for Ubuntu and Debian:

# Ubuntu / Debian: the build dependencies people always skip
sudo apt update
sudo apt install -y build-essential libssl-dev zlib1g-dev libbz2-dev \
  libreadline-dev libsqlite3-dev libncursesw5-dev xz-utils tk-dev \
  libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev curl git

# Install pyenv itself (clones into ~/.pyenv)
curl -fsSL https://pyenv.run | bash

Then wire it into your shell. Order matters: the init line adds the shims directory to the front of PATH, so it has to run near the end of your rc file. For bash, add this to ~/.bashrc (use ~/.zshrc and zsh in place of bash on zsh):

export PYENV_ROOT="$HOME/.pyenv"
[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init - bash)"
eval "$(pyenv virtualenv-init -)"

On macOS the story is shorter, because Homebrew supplies both pyenv and the headers CPython needs to build cleanly against a non-system OpenSSL:

# macOS via Homebrew
brew install pyenv pyenv-virtualenv
brew install openssl readline sqlite3 xz zlib tcl-tk

Open a new shell so the rc changes take effect, then confirm pyenv is on PATH with pyenv --version.

Build versions and pin them per project

A recent pyenv resolves a bare minor version to its latest patch release, so you rarely need to type a full 3.13.x. Build the two you want, set a machine-wide default, then pin individual projects from inside their directory:

# See what is on offer, then build from source
pyenv install --list | grep -E '^\s*3\.(12|13)\.'
pyenv install 3.12          # builds the latest 3.12.x
pyenv install 3.13          # builds the latest 3.13.x

# Machine-wide default (writes ~/.pyenv/version)
pyenv global 3.13

# Per project: pin from inside the project directory
cd ~/code/billing-api
pyenv local 3.12            # writes ./.python-version
python --version            # Python 3.12.x

That .python-version file is the whole trick. Commit it, and everyone who clones the repo and has pyenv gets the same interpreter the moment they cd into it. When pyenv decides which version a directory should use, it checks, in order: the PYENV_VERSION environment variable; the nearest .python-version file, searching from the current directory upward; then the global ~/.pyenv/version. First hit wins. That upward search is why a subdirectory inherits its parent’s pin unless it sets its own.

How the shims actually work

The reason python changes as you move between directories is not magic, it is a shim. pyenv puts ~/.pyenv/shims at the front of PATH and fills it with small stub executables, one per command name. When you run python, you are running the shim; it works out the correct version for the current directory using the precedence above and re-execs the real interpreter. You can see the difference plainly:

which python
# ~/.pyenv/shims/python        <- the shim, not a real interpreter

pyenv which python
# ~/.pyenv/versions/3.12.11/bin/python   <- the real one for this directory

# Installed a package that adds a command? Regenerate the shims:
pip install black
pyenv rehash
black --version

The one thing the shim mechanism cannot guess is a new command. Install a package that ships a console entry point and the shim will not exist until you run pyenv rehash. Most “command not found immediately after pip install” reports are exactly this. If you see one, rehash before you debug anything else.

Isolation with pyenv-virtualenv

A pinned interpreter still shares its site-packages across every project on that version. For real isolation, layer a virtual environment on top and pin the project to that instead of the bare version. Because we enabled virtualenv-init above, entering the directory activates it automatically:

# Create an isolated environment on top of 3.12
pyenv virtualenv 3.12 billing-api-3.12

# Pin the project to the environment instead of the bare version
cd ~/code/billing-api
pyenv local billing-api-3.12   # auto-activates on entry, deactivates on exit

Now the project has its own interpreter and its own packages, the system Python is untouched, and switching projects switches everything with a cd. This is the same instinct behind the baseline git config I set up on every machine and a sensible Renovate baseline: make the environment reproducible so nobody is debugging a machine instead of the code.

When it still goes wrong

Three failures cover almost everything. If an import of ssl or ctypes fails, you built Python before installing the dev libraries: install the full apt list above and rebuild that version with pyenv install. If python is still the system one after all this, your rc file either lacks the eval "$(pyenv init - bash)" line or has it above the PATH export; the init has to come last. And if a freshly installed command is not found, it is the rehash. None of these need the system interpreter touched, which is the entire point.

Getting developer environments consistent across a team is unglamorous and pays for itself every week. If your engineers are losing days to machine-specific breakage, my fractional CTO and delivery work covers exactly this kind of baseline. Engagements are fixed monthly retainers rather than day rates, so the cost is predictable. If a repeatable Python and tooling setup across your team would help, get in touch and I will show you what I put on a new machine.

Build and rescue work

Hands-on delivery of this kind is handled by Sixteen Pillars Studio.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Most technology problems are not technology problems. They are control problems.

The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.