What's the purpose of dictproxy?

后端 未结 2 1723
梦如初夏
梦如初夏 2020-12-23 21:50

The __dict__ of a type is a dictproxy object that is read only. I want to know what\'s the purpose of it. Is it only for \"don\'t allow modify buil

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-23 22:31

    The purpose of dictproxy (found in classes) is to allow for optimisations in the Python interpreter and to ensure its stability. See MartijnPieters comment below for details on the requirements for the optimisations, which apparently rely on the keys of class.__dict__ always being strings.

    dictproxy also seems to play a role in protecting against certain instabilities in the interpreter. For more information on one such instability, see the bug report and bug fix discussed on python.org with the title Bypassing __dict__ readonlyness. If you don't use some kind of proxy mechanism, then the __dict__ can be written to. If it can be written, it can be deleted. In the bug report they discuss some scenarios in which the __dict__ could be deleted and caused the interpreter to crash.

    Note that this contrasts with class instances, which you can assign to directly or with __setitem__():

    • instance.__dict__['x'] = 1

    Also, the instance __dict__ can be deleted. If it is deleted, then it gets automatically re-created when attribute assignment is attempted:

    del instance.__dict__ instance.a = 1 instance.__dict__

    Conclusion

    So in sum, dictproxy allows classes to operate more optimally and makes the interpreter more stable.

提交回复
热议问题