1 minute read

Installing Python on macOS

macOS comes with Python pre-installed, but it’s usually an older version. If you’re doing development work, you’ll likely want to install a newer version and set up a proper development environment.

The easiest way to install Python on macOS is using Homebrew, a package manager for macOS.

  1. First, install Homebrew if you don’t have it already:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  1. Then, install Python:
brew install python

This will install the latest version of Python 3.

  1. Verify the installation:
python3 --version

Using pyenv for Multiple Python Versions

If you need to work with multiple Python versions, pyenv is an excellent tool:

  1. Install pyenv using Homebrew:
brew install pyenv
  1. Add pyenv to your shell:
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc
source ~/.zshrc
  1. Install a specific Python version:
pyenv install 3.11.0
  1. Set a global Python version:
pyenv global 3.11.0

Setting Up Virtual Environments

For Python development, it’s best practice to use virtual environments to isolate project dependencies.

Using venv (built-in)

Python 3 comes with venv for creating virtual environments:

# Create a virtual environment
python3 -m venv myproject_env

# Activate the environment
source myproject_env/bin/activate

# Deactivate when done
deactivate

Using Poetry (Modern Python Project Management)

Poetry is a modern tool for Python dependency management and packaging:

  1. Install Poetry:
curl -sSL https://install.python-poetry.org | python3 -
  1. Create a new project:
poetry new myproject
cd myproject
  1. Add dependencies:
poetry add requests
  1. Activate the virtual environment:
poetry shell

Conclusion

With Python properly installed and configured with virtual environments, you’re ready to start developing Python applications on macOS. This setup ensures you have the right tools to manage dependencies and keep your projects isolated from each other.

Remember that using virtual environments is considered a best practice in Python development, as it helps avoid dependency conflicts between different projects.