Why should I use the __prepare__ method to get a class' namespace?

前端 未结 1 498
悲&欢浪女
悲&欢浪女 2021-02-05 10:58

Note This question is not about the Python 3 Enum data type, it\'s just the example I\'m using.

With PEP 3115 Python 3 added the _

相关标签:
1条回答
  • 2021-02-05 11:38

    Yes, there are risks.

    At least two reasons exist for getting the new namespace by calling __prepare__ instead of doing type(clsdict)():

    • When running on Python 2 clsdict is a dict, and the original __prepare__ never ran to begin with (__prepare__ is Python 3 only) -- in other words, if __prepare__ is returning something besides a normal dict, type(clsdict)() is not going to get it.

    • Any attributes set by __prepare__ on the clsdict would not be set when using type(clsdict)(); i.e. if __prepare__ does clsdict.spam = 'eggs' then type(clsdict)() will not have a spam attribute. Note that these attributes are on the namespace itself for use by the metaclass and are not visible in the namespace.

    To summarize: there are good reasons to use __prepare__() to obtain the proper class dictionary, and none for the type(clsdict)() shortcut.

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