Reputation: 31171
Given a trivial Python package with an __init__.py
:
$ ls -R foo/
foo/:
__init__.py bar.py
$ cat foo/bar.py
def do_stuff(): pass
$ cat foo/__init__.py
from .bar import *
I'm surprised that foo.bar
is defined:
>>> import foo
>>> foo.bar
<module 'foo.bar' from 'foo/bar.pyc'>
My understanding of from x import *
is that it doesn't define x
in the current scope. For example:
>>> from abc import *
>>> abc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
Why is foo.bar
defined in my first example, even though I don't have import bar
inside __init__.py
?
Upvotes: 4
Views: 197
Reputation: 16753
When you reference it by foo.bar
, it is not referencing to bar
used in the import statement in __init__.py
file, instead it is a reference to bar
module/file itself. Even if you remove all the code in __init__.py
file, import foo; foo.bar
would still work.
If that weren't the case, you wouldn't have been able to do something like this
import foo.bar
Since foo
is a package, as it contains __init__
file, hence it's internal files can be referenced directly.
Upvotes: 1