I'm often asked by students how to set up Python for their courses on their computers. Here are two methods:
- Using Homebrew + virtual environment (if you only ever need one version of Python)
- Using pyenv + virtual environment (if you need multiple Python versions)
First, a bit of explanation
- There are two major versions of Python: 2 and 3. Python 2 was deprecated a while ago, but there are still occasions where you might need it. For instance, I use Python 2 for ESP32 electronics development.
- When you run
python
in a shell on a fresh install of macOS, it is the system Python 2 installation that runs. This is a remnant of macOS, left behind for compatibility with legacy software. It will be removed in a future macOS release (possibly Big Sur). Until then, Mac owners are stuck with having to deal with legacy Python on their computer.- You'll probably run into errors if you try to
pip
install your dependencies with the system Python, which is why you want to follow one of the methods below to setup a recent version of Python on your machine.
- You'll probably run into errors if you try to
- A shell/terminal is a program you run commands in, e.g.
cd
,cat
orls
- There are many kinds of shell, but most Macs today running Catalina run
zsh
- When you hear the terms "add to your profile", "add to PATH" etc.; that means you're letting the shell know where to look for different programs/executables
- There are many kinds of shell, but most Macs today running Catalina run
Homebrew
Setup
You can alias python3
to python
by running the following, and restarting your shell:
Usage
Now you want to make something called a virtual environment, which is a walled-off garden where you can install your project's dependencies.
With the environment active, you should be able to install any dependencies and run all your Python 3 scripts. After installing Jupyter, for instance, you should be able to just run jupyterlab
and it will open up.
You can use the following command to deactivate the environment. This brings you back to system Python, and your dependencies will no longer be in scope:
Virtual environments are great because the moment you want to stop working on the project, you can just take the virtual environment folder and drag it to your trash.
Pyenv
If you want to use multiple versions of Python on your computer, I recommend pyenv
.
Here's a great reference: https://realpython.com/intro-to-pyenv/. TL;DR:
Setup
Add this to your .zshrc
to put pyenv
in scope:
Install a Python version:
Usage
Pyenv will automatically activate the virtual environment that was set using pyenv local
when you cd
to that folder. It does this using a .python-version
hidden file stored in the folder.