How does this Python import work?

python

Solution

A quote from the module docs (emphasis mine):

"When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

- the directory containing the input script (or the current directory).

- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

- the installation-dependent default."

Problem

I have two files in the same directory, and there are no `__init__.py` files anywhere: ``` c:\work\test>tree . |-- a | `-- a | |-- a1.py | `-- a2.py `-- b ``` one file imports the other: ``` c:\work\test>type a\a\a1.py print 'a1-start' import a2 print 'a1-end' c:\work\test>type a\a\a2.py print 'a2' ``` The import succeeds even when run from a completely different location: ``` c:\work\test\b>python ..\a\a\a1.py a1-start a2 a1-end ``` I'm running ``` c:\work\test>python -V Python 2.7.3 ``` and my PYTHONPATH and PYTHONHOME variables are not set ``` c:\work\test>echo %PYTHONPATH% %PYTHONHOME% %PYTHONPATH% %PYTHONHOME% ``` How does `a1.py` find `a2`?

Original source