Is it reliable and documented, how does PYTHONPATH populate sys.path?

On my machine, the values ​​from PYTHONPATH displayed in sys.path :

  • starting at index 1
  • saved order
  • de-duplicated

For example, with PYTHONPATH=/spam:/eggs:/spam , and then in python -m site , I get a result like:

 sys.path = [ something, '/spam', '/eggs', more, stuff, after ] 

It seems that this behavior is in Python 2 and Python 3. The question is, how is this PYTHONPATH processing documented / reliable, and what if it can be different on other platforms? Is it baked in the interpreter or processed by site.py and / or can be "modified" by system administrators?

I do not see this in the documentation here , it just says that sys.path "augmented" (and contrary to the documentation, non-existent directories do not seem to be ignored).

+8
python environment-variables python-import
source share
1 answer

Go down the list.


  • starting at index 1

It is reliable. As stated in the PYTHONPATH docs ,

The default search path is installation dependent, but generally starts with the / lib / pythonversion prefix (see PYTHONHOME above). It is always added to PYTHONPATH.

An additional directory will be inserted into the search path in front of PYTHONPATH, as described above in the "Interface Settings" section. The search path can be manipulated from a Python program as a sys.path variable.

One directory is inserted before PYTHONPATH, which may be the current directory, script directory, or another directory, depending on how you started Python. Other directories are added. The site module will also add some modules to sys.path , but site also adds:

Importing this module will add site-specific paths to the module search path and add some built-in ...


  • saved order

I don't think this is explicitly documented anywhere, but the search tracking order is important, and changing it is a backward compatibility lag. I do not think they will do frivolously.


  • de-duplicated

This is an undocumented effect of the site module. This will not happen if you run Python with the -S flag, which disables the site . You can see the code in site.removeduppaths

+4
source share

All Articles