Why does the shell run the incorrect Python?

I am coming from an Ubuntu environment, and since you can set Python 3 to be the first-class Python in Ubuntu (as in, you call python and you get Python 3), I wanted to do the same on the Mac I've started using.

After trying to point the /usr/bin/python symbolic link to /usr/bin/python3 and finding it failed, I did some research and found that Apple puts some protection on /usr/bin which has to be updated by changing a flag in Recovery mode, and is not generally recommended. So I thought I would create a new /usr/bin/local/python link to /usr/bin/python3 and that would work since /usr/bin/local/python comes before /usr/bin/python in the path.

Here's what I've tried. The results have me confused.

username@Machine ~ % python --version
Python 2.7.18
username@Machine ~ % sudo rm /usr/local/bin/python
username@Machine ~ % sudo ln -s /usr/bin/python3 /usr/local/bin/python
username@Machine ~ % which python
/usr/local/bin/python
username@Machine ~ % python --version
Python 2.7.18
username@Machine ~ % echo $PATH
/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
username@Machine ~ % /usr/bin/python3 --version
Python 3.8.9
username@Machine ~ % ls -l /usr/local/bin/python
lrwxr-xr-x  1 root  wheel  16 Dec  9 12:37 /usr/local/bin/python -> /usr/bin/python3
username@Machine ~ % hash -r
username@Machine ~ % python --version
Python 2.7.18
username@Machine ~ % whence python   
/usr/local/bin/python

I should add that I'm running zsh, and I'm used to running bash. Why don't I get version 3.8.9 when I run python --version or /usr/local/bin/python --version?


Because you didn't re-hash the shell you are currently in. Either use:

% hash -r

Or restart the shell.

/usr/bin/which does not tell you what the shell is going to do, because it is not a shell builtin... it searches $PATH.

If you want to know what the shell is actually going to do, use whence, which is a shell builtin.

Having said this, since you have decided to use Homebrew, why aren't you using Homebrew's python? Python 3.8.9 is the one from the Apple CLT.