Switch Python versions with pyenv
You can switch Python versions with pyenv using three main commands: global, local, and shell. The method you choose depends on the scope you want for the new Python version.
Switching Globally 🌍
The pyenv global command sets the default Python version for your entire user account. This version is used everywhere unless a local or shell-specific version overrides it. This is typically the version you'll use for most new projects.
-
Install the desired version: If you haven't already, install the Python version you want to use.
pyenv install 3.12.1 -
Set the global version:
pyenv global 3.12.1 -
Verify the change:
python --version
# Output: Python 3.12.1
Switching Locally (Per Project) 📂
The pyenv local command sets a Python version for a specific directory and all of its subdirectories. This is the most common use case for developers, as it allows each project to have its own isolated Python version.
-
Navigate to your project directory.
cd my-project -
Set the local version: This command creates a hidden file named
.python-versionin the current directory. When you enter this directory,pyenvwill automatically switch to the version specified in the file [1, 5].pyenv local 3.10.5 -
Verify the change:
python --version
# Output: Python 3.10.5If you move to a different directory, the
globalversion will be active again unless a differentlocalversion is set.
Switching for a Single Shell Session 🐚
The pyenv shell command sets a Python version for the current terminal session only. This is useful for temporary work or testing and will be reset once you close the terminal or start a new one [1].
-
Set the shell version:
pyenv shell 3.9.0 -
Verify the change:
python --version
# Output: Python 3.9.0The
shellcommand takes precedence over bothlocalandglobalsettings [2]. To unset it, you can runpyenv shell --unset.
Command Precedence ⚙️
pyenv resolves which Python version to use based on a specific order of precedence, from highest to lowest [2]:
pyenv shell(from thePYENV_VERSIONenvironment variable)pyenv local(from the.python-versionfile in the current directory)pyenv global(from the~/.pyenv/versionfile) This video provides a step-by-step guide to installing Pyenv and managing different Python versions on macOS, which is a great follow-up once you have Pyenv installed. Manage Multiple Python Versions with PyEnv
