How does this Python import work?

I have two files in one directory and there are no __init__.py files anywhere:

 c:\work\test>tree . |-- a | `-- a | |-- a1.py | `-- a2.py `-- b 

one file imports another:

 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' 

Import was successful even when starting from a completely different place:

 c:\work\test\b>python ..\a\a\a1.py a1-start a2 a1-end 

I run

 c:\work\test>python -V Python 2.7.3 

and my variables PYTHONPATH and PYTHONHOME are not set

 c:\work\test>echo %PYTHONPATH% %PYTHONHOME% %PYTHONPATH% %PYTHONHOME% 

How a1.py find a2 ?

+5
source share
1 answer

Quote from the docs document (my attention):

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

  • The directory containing the script input (or the current directory).
  • PYTHONPATH (a list of directory names with the same syntax as the PATH shell variable).
  • installation-dependent default value.
+8
source

Source: https://habr.com/ru/post/1208263/


All Articles