Skip to main content

Switch Python versions with pyenv

Β· 4 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

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.

  1. Install the desired version: If you haven't already, install the Python version you want to use.

    pyenv install 3.12.1
  2. Set the global version:

    pyenv global 3.12.1
  3. 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.

  1. Navigate to your project directory.

    cd my-project
  2. 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
  3. Verify the change:

    python --version
    # Output: Python 3.10.5

    If you move to a different directory, the global version will be active again unless a different local 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].

  1. Set the shell version:

    pyenv shell 3.9.0
  2. Verify the change:

    python --version
    # Output: Python 3.9.0

    The shell command takes precedence over both local and global settings [2]. To unset it, you can run pyenv shell --unset.

Command Precedence βš™οΈβ€‹

pyenv resolves which Python version to use based on a specific order of precedence, from highest to lowest [2]:

  1. pyenv shell (from the PYENV_VERSION environment variable)
  2. pyenv local (from the .python-version file in the current directory)
  3. 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