As far as I understand from the python docs, from package import x statement should bind only x, but not package, into the current namespace.
But in practice, if package is a relative name, it is also bound sometimes!
Let me provide an example. Consider the following file hierarchy:
root/
package/
__init__.py
subpackage/
__init__.py
subpackage/__init__.py:
foo = 42
package/__init__.py:
from os import name
from .subpackage import foo
print(globals().get('name'))
print(globals().get('os'))
print(globals().get('foo'))
print(globals().get('subpackage'))
Now let's run python (either v2 or v3) interpreter from the root directory and execute
>>> import package
The first three output lines are predictable:
posix
None
42
But the last one is <module 'package.subpackage' ...> rather than None, and this confuses me somewhat.
Have I missed something? Is it expected behavior? What is the reason?
The situation seems even more weird to me in this case:
root/
__init__.py # Empty.
package/
__init__.py
another_package/
__init__.py
another_package/__init__.py:
bar = 33
package/__init__.py:
from ..another_package import bar
print(globals().get('another_package'))
Now I run this outside the root:
>>> import root.package
None # OK.
>>> dir(root.package)
['__builtins__', ..., '__path__', 'bar'] # OK.
>>> dir(root)
['__builtins__', ..., '__path__', 'another_package', 'package'] # What?!
Why did another_package appear in dir(root)?