I'm often asked by students how to set up Python for their courses on their computers. Here are two methods:
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 (update: Python 2 was finally removed in Monterey 12.3 🎉). Until then, Mac owners are stuck with having to deal with legacy Python on their computer.
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.cd
, cat
or ls
zsh
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" # install homebrew
brew install python # install python
python # test to see if it works
python3 # alternatively, use this command
You can alias python3
to python
by running the following, and restarting your shell:
echo "alias python=/usr/local/bin/python3" >> ~/.zshrc
Now you want to make something called a virtual environment, which is a walled-off garden where you can install your project's dependencies.
python3 -m venv [path to your folder]/[desired name] # create venv (one-time)
source [path to your created environment]/bin/activate # this is how you activate it
pip install jupyter jupyterlab numpy pandas tensorflow etc. # install all your 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:
deactivate
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.
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:
curl https://pyenv.run | bash # install pyenv
Add this to your .zshrc
to put pyenv
in scope:
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
Install a Python version:
pyenv install --list # see which ones are available
pyenv install 3.8 # pick one
pyenv global 3.8 # set a Python version globally
pyenv local 3.8 # set a Python version on a per-folder basis
python -V # check version to confirm
pyenv virtualenv [python_version] [environment_name] # create environment (one-time)
pyenv local [environment_name] # activate it
source deactivate # deactivate it
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.