Why is a class __dict__ a mappingproxy?

后端 未结 3 1555
长情又很酷
长情又很酷 2020-12-02 18:21

I wonder why a class __dict__ is a mappingproxy, but an instance __dict__ is just a plain dict

>>&g         


        
3条回答
  •  时光说笑
    2020-12-02 18:28

    Since Python 3.3 mappingproxy type was renamed from dictproxy. There was an interesting discussion on this topic.

    It's a little bit hard to find the documentation for this type, but the documentation for vars method describes this perfectly (though it wasn't documented for a while):

    Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a types.MappingProxyType to prevent direct dictionary updates).

    If you need to assign a new class attribute you could use setattr. It worth to note that mappingproxy is not JSON serializable, check out the issue to understand why.


    Also the history of this type is a quite interesting:

    • Python 2.7: type(A.__dict__) returns as type(dict()), and it's possible to assign new attributes through __dict__, e.g. A.__dict__['foo'] = 'bar'.

    • Python 3.0 - 3.2: type(A.__dict__) returns , the difference now a little bit more clear. Trying to assign a new attribte gives TypeError. There was an attempt to add dictproxy as a public builtin type.

    • Python 3.3: adds type, that described above.

提交回复
热议问题