How to set python environment variable PYTHONPATH on Mac?

PYTHONPATH is an environment variable that tells Python where to look for modules when importing. On Mac, there are several methods to set PYTHONPATH depending on your shell and persistence needs.

Method 1: Temporary Setting (Current Session Only)

Set PYTHONPATH for the current terminal session only ?

export PYTHONPATH=/path/to/your/modules

This setting is lost when you close the terminal.

Method 2: Permanent Setting Using .bash_profile

For Bash shell users, add PYTHONPATH to your profile file ?

Step 1: Open Terminal and navigate to your home directory ?

cd ~

Step 2: Create or open .bash_profile ?

touch .bash_profile
open -e .bash_profile

Step 3: Add the export command to the file ?

export PYTHONPATH="/Users/username/python-modules"

Step 4: Apply changes by restarting Terminal or running ?

source ~/.bash_profile

Method 3: For Zsh Shell (macOS Catalina and Later)

Modern Macs use Zsh by default. Add PYTHONPATH to .zshrc ?

echo 'export PYTHONPATH="/Users/username/python-modules"' >> ~/.zshrc
source ~/.zshrc

Common PYTHONPATH Configurations

Here are practical examples for different scenarios ?

Single Directory

export PYTHONPATH="/Users/username/my-python-modules"

Multiple Directories

export PYTHONPATH="/Users/username/modules:/Users/username/packages"

Adding to Existing PYTHONPATH

export PYTHONPATH="$PYTHONPATH:/new/path/to/modules"

Using Home Directory Shortcut

export PYTHONPATH="~/python-modules"

Verification

Verify PYTHONPATH is set correctly ?

import sys
print(sys.path)

Or check from command line ?

echo $PYTHONPATH

Best Practices

Use Virtual Environments: Instead of modifying global PYTHONPATH, consider using virtual environments for project-specific dependencies.

Avoid Wildcards: Don't use wildcards (*) in PYTHONPATH as they can cause unexpected behavior.

Check Your Shell: Run echo $SHELL to determine whether you're using Bash or Zsh.

Conclusion

Setting PYTHONPATH on Mac ensures Python can locate your custom modules. Use .zshrc for modern Macs or .bash_profile for older versions. Consider virtual environments for better project isolation.

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

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements