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*

Imports in __init__.py

This is my project structure (Python 3.5.1.):

a
├── b.py
└── __init__.py

Case 1

  • File b.py is empty.

  • File __init__.py is:

    print(b)
    

If we run import a, the output is:

NameError: name 'b' is not defined

Case 2

  • File b.py is empty.

  • File __init__.py is:

    import a.b
    print(b)
    

If we run import a, the output is:

<module 'a.b' from '/tmp/a/b.py'>

Question

Why doesn't the program fail in Case 2?

Usually if we run import a.b then we can only reference it by a.b, not b. Hopefully somebody can help explain what's happening to the namespace in Case 2.

Answer*

Draft saved
Draft discarded
Cancel

lang-py

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