有没有办法让python pickle忽略“它不是同一对象"?错误 [英] Is there a way to make python pickle ignore "it's not the same object " errors
问题描述
有没有办法让python pickle忽略它不是同一对象"错误?
Is there a way to make python pickle ignore "it's not the same object " errors?
我正在使用Mock编写测试,以对datetime.utcnow()产生的结果进行精细控制.我正在使用的代码对时间敏感,因此模拟补丁可使其易于测试.
I'm writing a test using Mock to have fine grain control over the results that datetime.utcnow() produces. The code I'm using is time sensitive so mock's patch makes it easy to test.
相同的测试需要腌制对象并将结果发送到远程服务器.出于测试目的,如果标准日期时间是由远程服务器腌制并接收的,则一切正常.
The same tests need to pickle objects and send the results to a remote server. For the purpose of the test if a standard datetime was pickled and received by the remote server everything would be fine.
不幸的是,泡菜模块正在倒装,并出现以下错误:
Unfortunately the pickle module is barfing with the following error:
无法腌制<键入'datetime.datetime'> ;:与以下对象不同 datetime.datetime
Can't pickle <type 'datetime.datetime'>: it's not the same object as datetime.datetime
这是重现该错误的最小示例.
Here is a minimal example to reproduce the error.
from mock import patch
from datetime import datetime
import pickle
class MockDatetime(datetime):
frozendt = datetime(2011,05,31)
@classmethod
def advance(cls, **kw):
cls.frozendt = cls.frozendt + timedelta(**kw)
@classmethod
def utcnow(cls):
return cls.frozendt
@patch('datetime.datetime', MockDatetime)
def test():
pickle.dumps(datetime.utcnow())
if __name__ == '__main__':
test()
是否存在某些__reduce__
和__getstate__
方法的组合,可能会使泡菜机械误以为MockDatetime是我泡菜时的日期时间?
Is there some combo of __reduce__
and __getstate__
methods that might trick the pickle machinery into thinking MockDatetime is a datetime when I pickle?
推荐答案
Looking at the where to patch section in the documentation I see this advice:
基本原理是在使用的地方打补丁,该地方不一定与定义的地方相同.
The basic principle is that you patch where an object is used, which is not necessarily the same place as where it is defined.
按照此建议,我尝试替换:
Following this recommendation, I've tried to replace:
@patch('datetime.datetime', MockDatetime)
具有:
@patch('__main__.datetime', MockDatetime)
,我没有从pickle
收到任何错误.另外,我添加了print
语句以确保datetime
确实已被修补,并且我获得了预期的值.
and I didn't get any error from pickle
. Also, I added a print
statement to make sure that datetime
was really being patched and I got the expected value.
这篇关于有没有办法让python pickle忽略“它不是同一对象"?错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!