Why should I use __all__ in __init__ of python package?

后端 未结 1 1544
梦如初夏
梦如初夏 2021-02-04 20:25

I\'ve already read Can someone explain __all__ in Python? and I understand that it only affects from ... import * statements, but I can\'t figure out a real use cas

相关标签:
1条回答
  • 2021-02-04 20:54

    The only time you want to define __all__ in your package's __init__.py is to list the names of "exported" members that you want to export for when a user does:

    from package import *
    

    This is documented in 6.4.1. Importing * From a Package

    Note: If you don't define an __all__ in your package then the default behaviour is as follows (from the documentation):

    If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements. Consider this code:

    A "naive" interpretation of this can be:

    If you don't define __all__; a from package import * will bring in everything from that package and anything imported in that pacakge's __init__.py.

    0 讨论(0)
提交回复
热议问题