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-version
in the current directory. When you enter this directory,pyenv
will 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
global
version will be active again unless a differentlocal
version 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
shell
command takes precedence over bothlocal
andglobal
settings [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_VERSION
environment variable)pyenv local
(from the.python-version
file in the current directory)pyenv global
(from the~/.pyenv/version
file) 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