Explain Codes LogoExplain Codes Logo

How do I use brew installed Python as the default Python?

python
venv
best-practices
tools
Anton ShumikhinbyAnton Shumikhin·Dec 22, 2024
TLDR

To use Homebrew's Python as the default Python interpreter, add its bin directory to your PATH:

echo 'export PATH="/usr/local/opt/python/libexec/bin:$PATH"' >> ~/.zshrc

To make this change for bash, substitute ~/.zshrc with ~/.bash_profile. To put this into immediate effect, source the file:

source ~/.zshrc

Now, when you run python --version, it will show the version installed via Homebrew.

Prioritizing command line resource

When you modify the PATH, the order matters significantly. By prefixing the Homebrew bin path to your PATH, the shell will prioritize Homebrew's Python whenever 'python' is invoked. A small step for your shell, a giant leap for your Python comfort!

In case you have symlinked python to python3 based on previous guidelines:

ln -s -f /usr/local/bin/python3 /usr/local/bin/python

For added certainty of proper linking with Homebrew, do this:

brew link --overwrite python

You've now ensured Homebrew's Python takes precedence through symbolic linking. Homebrew Python says "I'm the captain now!"

System-wide Python Interpreter

In some circumstances, you might want to change default Python version at the system level. This can be accomplished by modifying /etc/paths. However, proceed with caution, as this could potentially impact system-level tasks and processes relying on default Python.

To ensure your shell sessions find the correct Homebrew paths, it's crucial to evaluate:

eval "$(brew shellenv)"

This command permits zsh or other shell types to be aware of Homebrew's environment settings. It's like giving your shell a map to treasure land!

Confirming and troubleshooting set-up

After the changes, verify the new set-up using which python. If everything is done correctly, this command will print /usr/local/bin/python. Also, the version checks python --version and pip -V would display Homebrew's version.

For troubleshooting any missteps or concerns, get a visit from the doctor:

brew doctor

This command diagnoses common issues with path configurations and offers remedies. It's saving Python lives, one terminal at a time!

Staying up-to-date

Keep in touch with Homebrew's updates and follow their advice. Homebrew will often notify you with important post-installation directions to ensure a seamless workflow with the latest software.

Handling multiple Python versions

In case you're juggling multiple Python versions, pyenv becomes a great resource. It enables switching between Python versions on a per-project basis, without affecting the entire system setting.