Can someone explain __all__ in Python?

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

    Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from import * is used on the module.

    For example, the following code in a foo.py explicitly exports the symbols bar and baz:

    __all__ = ['bar', 'baz']
    
    waz = 5
    bar = 10
    def baz(): return 'baz'
    

    These symbols can then be imported like so:

    from foo import *
    
    print(bar)
    print(baz)
    
    # The following will trigger an exception, as "waz" is not exported by the module
    print(waz)
    

    If the __all__ above is commented out, this code will then execute to completion, as the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace.

    Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package

    NOTE: __all__ affects the from import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from import .

提交回复
热议问题