Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

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*

Draft saved
Draft discarded
Cancel
3
  • 1
    How do you know it takes precedence? – I couldn't find it in the Python documentation Commented Jan 10, 2017 at 21:56
  • @qff I tested it. I also tested python3 just now and it has the same behavior. A link to official documentation of the fact would be good. If you find one, please feel free to edit my answer or post a comment and I'll edit it. Commented Jan 10, 2017 at 22:14
  • 1
    Found it! (kind of) – the entries of a directory are sorted before trying to load each one as either a package or module. This ensures packages are loaded first. Link to CPython source code Commented Jan 10, 2017 at 22:58

lang-py

AltStyle によって変換されたページ (->オリジナル) /