Can someone explain __all__ in Python?

前端 未结 11 2422
一个人的身影
一个人的身影 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:54

    __all__ affects how from foo import * works.

    Code that is inside a module body (but not in the body of a function or class) may use an asterisk (*) in a from statement:

    from foo import *
    

    The * requests that all attributes of module foo (except those beginning with underscores) be bound as global variables in the importing module. When foo has an attribute __all__, the attribute's value is the list of the names that are bound by this type of from statement.

    If foo is a package and its __init__.py defines a list named __all__, it is taken to be the list of submodule names that should be imported when from foo import * is encountered. If __all__ is not defined, the statement from foo import * imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py.

    Note that __all__ doesn't have to be a list. As per the documentation on the import statement, if defined, __all__ must be a sequence of strings which are names defined or imported by the module. So you may as well use a tuple to save some memory and CPU cycles. Just don't forget a comma in case the module defines a single public name:

    __all__ = ('some_name',)
    

    See also Why is “import *” bad?

提交回复
热议问题