Imports in an __init__.py
seem to behave differently when the file is run, to when it is imported.
If we have the following files:
run.py
:
import test
test/b.py
:
class B(object):
pass
test/__init__.py
:
from b import B
print B
print b
If we run __init__.py
we get an error as I expect:
% python test/__init__.py
<class 'b.B'>
Traceback (most recent call last):
File "test/__init__.py", line 6, in <module>
print b
NameError: name 'b' is not defined
But if we run.py
then we don't:
% python run.py
<class 'test.b.B'>
<module 'test.b' from '~/temp/test/b.py'>
I would expect the behaviour to be the same. Why does this work?
This only works if we do it in an __init__.py
. If we:
mv __init__.py a.py
touch __init__.py
and make run.py
:
import test.a
Then we do get the error.
The situation is the following: you have a script (
run.py
), a packagetest
and its submoduletest.b
.Whenever you import a submodule in Python, the name of that submodule is automatically stored into the parent package. So that when you do
import collections.abc
(orfrom collections.abc import Iterable
, or similar), the packagecollections
automatically gets the attributeabc
.This is what's happening here. When you do:
the name
b
is automatically loaded intotest
, becauseb
is a submodule of thetest
package.Even if you don't do
import b
explicitly, whenever you import that module, the name is placed intotest
. Becauseb
is a submodule oftest
, and it belongs totest
.Side node: your code won't work with Python 3, because relative imports have been removed. To make your code work with Python 3, you would have to write:
This syntax is perfectly identical to
from b import B
, but is much more explicit, and should help you understand what's going on.Reference: the Python reference documentation also explains this behavior, and includes a helpful example, very similar to this situation (the difference is just that an absolute import is used, instead of a relative import).