具有__name__属性的Pickle Mock / MagicMock对象

时间:2019-11-13 06:28:35

标签: python pickle

Mock / MagicMock没有默认的__name__属性,我是手动添加的。

运行以下代码段时:

import pickle
from mock import MagicMock

m = MagicMock()
m.__name__ = 'my name'
m.__reduce__ = lambda self: (MagicMock, ())

print(m.__name__)

b = pickle.dumps(m)

pickled_m = pickle.loads(b) 
print(pickled_m.__name__) 

我遇到错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/.../.pyenv/virtualenv/lib/python3.6/site-packages/mock/mock.py", line 716, in __getattr__
    raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute '__name__'

如何指示泡菜序列化__name__属性?

1 个答案:

答案 0 :(得分:0)

您的问题与pickle无关,您的MagicMock类具有__getattr__魔术方法的自定义实现,在某些情况下会引发AttributeError异常。为了证明这一点,请使用以下代码:

import pickle
class A():
  a = 10

a = A()
a.__name__ = "A"
ap = pickle.dumps(a)
na = pickle.loads(ap)
print(na.__name__)

将输出:

'A'

因此__name__的酸洗和酸洗没有问题。