Using pyenv for Python version management

Python is currently the 2nd most used programming language in the world. Development tools are increasing in quality as well, making life as a Python developer much easier (shoutout to Visual Studio Code, poetry, black and flake8). Most of the time you use only the Python version installed in your operating system. However, projects can require different Python versions, sometimes even made explicit thanks to poetry.

pyenv is a cli-utility that solves this problem by making it easy to manage Python versions. It is easy to setup:

  1. Follow the instructions on Github:. I prefer the GitHub Checkout way of installing, it's super easy. It's a simple git clone command.
  2. Make sure the relevant environment variables get added to your bash, zsh or fish shell.
  3. Restart your shell to make path changes take effect.
  4. You need to install build dependencies so that you can install any Python version you want. For Ubuntu you need to use the following command:
    sudo apt-get update; sudo apt-get install --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
    Please take a look at the instructions to find out how to install build dependencies for your OS

Now you can use pyenv! Some things you can do are:

  • pyenv versions View all the installed Python versions
  • pyenv install 3.9.0 Install Python 3.9.0. It can be ofcourse any version you want. It may take a while to install a new Python versions
  • pyenv global <version> Change the global Python version

You can also create a .python-version file that will tell pyenv which Python version should be used (the content of the file should be the desired Python version). It works like this:

> pyenv versions
* system (set by /home/marco/.pyenv/version)

> python -V
Python 3.8.2

> cd my-python-project

> cat .python-version

> python -V
Python 3.9.0

Pretty cool if you ask me!

Show Comments