Python: Ensuring my class gets pickled only with the latest protocol

本秂侑毒 提交于 2019-12-07 13:42:57

问题


I'm developing a class which can be meaningfully pickled only using protocol 2 (and upwards on Python 3.) When an older protocol is used, hard-to-trace bugs happen. I want to save the users of the class some debugging pain, so I want the class to immediately raise an exception if it's being pickled with a protocol of less than 2.

How can I do that?


回答1:


You can implement the __reduce_ex__() method on your class. It receives one parameter, which is the protocol version. Simply raise an exception if the version is not 2.



来源:https://stackoverflow.com/questions/5570680/python-ensuring-my-class-gets-pickled-only-with-the-latest-protocol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!