How to set your python path on Mac?

Setting the PYTHONPATH on macOS helps Python locate modules and packages in custom directories. While there are several methods available, it's important to understand when and why to use each approach.

What is PYTHONPATH?

PYTHONPATH is an environment variable that tells Python where to look for modules and packages beyond the standard library and site-packages directories.

Method 1: Temporary Export (Current Session Only)

This method sets PYTHONPATH for the current terminal session only ?

export PYTHONPATH="${PYTHONPATH}:${HOME}/foo"

This adds the foo directory in your home folder to Python's search path. The ${PYTHONPATH}: part preserves any existing PYTHONPATH values.

Method 2: Permanent Setup via Shell Profile

To make the change permanent, add the export command to your shell profile file ?

For Bash Users

echo 'export PYTHONPATH="${PYTHONPATH}:${HOME}/foo"' >> ~/.bashrc
source ~/.bashrc

For Zsh Users (macOS Default)

echo 'export PYTHONPATH="${PYTHONPATH}:${HOME}/foo"' >> ~/.zshrc
source ~/.zshrc

Method 3: Using Python's sys.path (Programmatic)

You can also modify the path directly within your Python script ?

import sys
import os

# Add custom directory to Python path
sys.path.append(os.path.expanduser('~/foo'))

# Verify the path was added
print("Python search paths:")
for path in sys.path:
    print(f"  {path}")
Python search paths:
  /Users/username/current_directory
  /usr/local/lib/python3.x/site-packages
  ...
  /Users/username/foo

Verifying PYTHONPATH

Check if your PYTHONPATH is set correctly ?

import os
import sys

# Check PYTHONPATH environment variable
pythonpath = os.environ.get('PYTHONPATH', 'Not set')
print(f"PYTHONPATH: {pythonpath}")

# Check sys.path (actual search paths Python uses)
print("\nPython search paths:")
for i, path in enumerate(sys.path):
    print(f"{i}: {path}")

Best Practices and Alternatives

Method Use Case Pros Cons
PYTHONPATH System-wide modules Simple setup Can cause conflicts
Virtual Environments Project isolation Clean separation Extra setup
pip install -e Development packages Proper packaging Requires setup.py

Important Warnings

In most cases, modifying PYTHONPATH is not the recommended approach. Consider these alternatives first ?

  • Virtual Environments: Use venv or conda for project isolation
  • Package Installation: Use pip install -e . for development packages
  • Proper Project Structure: Organize code as installable packages

Conclusion

While PYTHONPATH can be set using export commands, it's generally better to use virtual environments or proper package installation. Only modify PYTHONPATH when you specifically need system-wide access to custom modules.

Updated on: 2026-03-24T16:57:58+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements