Why does importing characters from a module also define a module character?

Given a trivial Python package with __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 am surprised that it foo.baris determined:

>>> import foo
>>> foo.bar
<module 'foo.bar' from 'foo/bar.pyc'>

My understanding from x import *is that it does not define xin the current area. For instance:

>>> from abc import *
>>> abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined

Why is foo.bardefined in my first example, although I haven't import barinside __init__.py?

+4
source share
1 answer

When you reference it foo.bar, it does not refer to barthat used in the import statement in the file __init__.py, instead it refers to barthe module / file itself. Even if you delete all the code in the __init__.pyfile, import foo; foo.barit will still work.

, -

import foo.bar

foo - , __init__, .

+1

Source: https://habr.com/ru/post/1687894/


All Articles