Jeeyoung Kim Jeeyoung Kim - 29 days ago 17
Python Question

Python import precedence: packages or modules?

I wasn't clear how to correctly name this question.

Case 1

Assume that I have the following directory structure.

foo
|
+- bar/__init__.py
|
+- bar.py


If I have

from foo import bar


How do I know which bar (
bar.py
or
bar/__init__.py
) is being imported? Is there any easy way to automatically detect this from occurring?

Case 2

foo
|
+- foo.py
|
+- other.py


If other.py has the line

import foo


How do I know which foo (foo or foo.foo) is being imported? Again, is tehre any easy way to automatically detect this from occurring?

Answer

From the docs: "When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names."

Note that "current directory" is relative to the main script path (the one where __name__ == '__main__' is True). So if you are at /home/billg calling /foo/bar.py, "current directory" refers to /foo.