Can someone explain __all__ in Python?

前端 未结 11 2439
一个人的身影
一个人的身影 2020-11-21 13:36

I have been using Python more and more, and I keep seeing the variable __all__ set in different __init__.py files. Can someone explain what this d

11条回答
  •  别跟我提以往
    2020-11-21 13:49

    Short answer

    __all__ affects from import * statements.

    Long answer

    Consider this example:

    foo
    ├── bar.py
    └── __init__.py
    

    In foo/__init__.py:

    • (Implicit) If we don't define __all__, then from foo import * will only import names defined in foo/__init__.py.

    • (Explicit) If we define __all__ = [], then from foo import * will import nothing.

    • (Explicit) If we define __all__ = [ , ... ], then from foo import * will only import those names.

    Note that in the implicit case, python won't import names starting with _. However, you can force importing such names using __all__.

    You can view the Python document here.

提交回复
热议问题