Installing Python on macOS
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.
Using Homebrew (Recommended)
The easiest way to install Python on macOS is using Homebrew, a package manager for macOS.
- First, install Homebrew if you don’t have it already:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Then, install Python:
brew install python
This will install the latest version of Python 3.
- 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:
- Install pyenv using Homebrew:
brew install pyenv
- Add pyenv to your shell:
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc
source ~/.zshrc
- Install a specific Python version:
pyenv install 3.11.0
- 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:
- Install Poetry:
curl -sSL https://install.python-poetry.org | python3 -
- Create a new project:
poetry new myproject
cd myproject
- Add dependencies:
poetry add requests
- 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.