gpt4 book ai didi

python - 创建无法 pickle 的对象

转载 作者:太空狗 更新时间:2023-10-30 00:48:52 25 4
gpt4 key购买 nike

我如何轻松地创建一个不能被 pickle 的对象来测试我的 rpc 代码中的边缘情况?

它需要是:

  1. 简单
  2. 可靠(预计不会在未来版本的 python 或 pickle 中崩溃)
  3. 跨平台

编辑:预期用途看起来像这样:

class TestRPCServer:
def foo(self):
return MagicalUnpicklableObject()

def test():
with run_rpc_server_and_connect_to_it() as proxy:
with nose.assert_raises(pickle.PickleError):
proxy.foo()

最佳答案

如果您只需要一个在 pickle 时会抛出异常的对象,为了测试的目的,您可以炸毁 __getstate__ method .

>>> class C:
... def __getstate__(self):
... raise Exception
...
>>> pickle.dumps(C())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 723, in save_inst
stuff = getstate()
File "<stdin>", line 3, in __getstate__
Exception

如果您想要一个不那么人为的场景,请考虑使用操作系统资源(如文件句柄、套接字或线程等)的对象。

>>> with open('spam.txt', 'w') as f:
... pickle.dumps(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle file objects

关于python - 创建无法 pickle 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com