Specifying Your Python Version
One of the more confusing parts of
pyenv is how exactly the
python command gets resolved and what commands can be used to modify it.
As mentioned in the previous lesson where we looked at the
pyenv commands, there are three ways to modify which version of Python you’re using.
So, how do all these commands interact with one another? The resolution order looks like this.
pyenv starts to look for the
PYENV_VERSION environment variable, which is set with the
pyenv shell command.
PYENV_VERSION environment variable isn’t set, then
pyenv will check whether a
.python-version file is found in the current folder or one of the parent folders, which would have been created by the
pyenv local command.
.python-version file is found, then
pyenv will check which version is set in the file located at
And when no version is set there,
pyenv will use system Python.
Now let’s have a look in the terminal what this exactly looks like. Let’s start with the
pyenv version command. You will see that currently
system Python is used, which means that at this moment
pyenv doesn’t really do anything for us.
Let’s start to apply its power by running
pyenv global 3.9.1 and have another look at the output of
You can see that now
pyenv wants to use 3.9.1 as our Python version. It even indicates the location of the file it found. That file does indeed exist and you can just
cat its contents.
But now you would still have to change the Python version with the
pyenv global command each time you want to switch projects, which isn’t very convenient.
Let’s fix that with the
pyenv local command. Let’s move into the project directory, run
pyenv local 3.8.7 if you haven’t already done so in a previous lesson, and have another look at the output of
pyenv version. Here again,
pyenv indicates how it would resolve our
This time it comes from
.python-version in your project directory.
The searching for
.python-version is recursive, which can be proven by creating a new directory within the project, moving into it, and running
Even though there isn’t a
.python-version in the subdirectory, the version is still set to
3.8.7 because the
.python-version file exists in a parent directory.
03:38 So now you can use the system Python interpreter, set the Python version to be used globally, and set the Python version to be used for a single project.
But what if you just want to experiment with another Python interpreter, for example, when you want to try some new features of a new dev release? Just run
pyenv shell 3.9-dev, which indicates you want to test
3.9-dev, and check the version.
pyenv shell command did is set the
PYENV_VERSION environment variable, as you can see when you
In this lesson, you have learned how exactly
pyenv resolves the
python command. In the next lesson, we’ll have a look at another very powerful concept used by Python developers: virtual environments.
Become a Member to join the conversation.