What's the purpose of the “__package__” attribute in Python?

后端 未结 2 1969
难免孤独
难免孤独 2020-12-05 02:18

All I want to know is what exactly does __package__ mean? Didn\'t find any explanation in the official doc, even on SO.

If you could pr

2条回答
  •  暖寄归人
    2020-12-05 02:34

    See the PEP 366 and import system reference documentation:

    The major proposed change is the introduction of a new module level attribute, __package__. When it is present, relative imports will be based on this attribute rather than the module __name__ attribute.

    and

    • The module’s __package__ attribute should be set. Its value must be a string, but it can be the same value as its __name__. If the attribute is set to None or is missing, the import system will fill it in with a more appropriate value. When the module is a package, its __package__ value should be set to its __name__. When the module is not a package, __package__ should be set to the empty string for top-level modules, or for submodules, to the parent package’s name. See PEP 366 for further details.

    So, for a module located in foo/bar/baz.py, __name__ is set to foo.bar.baz, and __package__ is set to foo.bar, while foo/bar/__init__.py will have foo.bar for both the __name__ and __package__ attributes.

提交回复
热议问题