如何检查物体是否可腌制 [英] How to check if an object is pickleable

查看:83
本文介绍了如何检查物体是否可腌制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要腌制的各种类型的对象的列表.我只想腌制那些可腌制的.除了尝试腌制对象外,是否有标准的方法来检查对象是否属于可腌制类型?

I have a list of objects of various types that I want to pickle. I would like to pickle only those which are pickleable. Is there a standard way to check if an object is of pickleable type, other than trying to pickle it?

文档说,如果发生了酸洗异常,那么可能已经在将某些字节写入文件后就已经发生了,因此尝试对对象进行酸洗作为测试似乎不是一个好的解决方案.

The documentation says that if a pickling exception occurs it may be already after some of the bytes have been written to the file, so trying to pickle the objects as a test doesn't seem like a good solution.

我看到了这篇文章,但没有回答我的问题.

I saw this post but it doesn't answer my question.

推荐答案

在这种情况下,我会建议进行鸭子测试.尝试将其放入合适的临时文件或内存文件中,如果失败,则丢弃结果,如果重新命名成功,则丢弃结果.

I would propose duck testing in this case. Try to pickle into a temporary file or a memory file, as you find suitable, then if it fails discard the result, if it succeeds rename.

为什么?

在python中,您可以通过两种方式检查对象是否具有某些属性.

In python you can check if the object has some properties in two ways.

检查object是否是某些抽象基类的实例.例如. Number 数字层次结构的根.如果您只想检查参数x是否为数字,而不必关心哪种类型,请使用isinstance(x,Number)."

Check if object is an instance of some Abstract Base Class. E.g. Number "The root of the numeric hierarchy. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number)."

或者尝试一下,然后处理异常.这在许多情况下都会发生.蟒蛇哲学基于鸭子. 鸭子输入 鸭测试

Or try it and then handle exceptions. This occurs during many occasions. The pythonic philosopy is based around the duck. Duck typing, duck test, and EAFP are the keywords.

我什至认为第一个已经在社区的压力下使用python3进行了适当的介绍,而许多人仍然坚信 duck 是使用python的方法.

I even believe the 1st one has been properly introduced with python3 under the pressure from the part of the community, while many still strongly believe duck is the way to go with python.

AFAIK没有可以检查的特殊前提条件,也没有任何 ABC 该对象可以在酸洗的情况下进行检查.所以剩下的就是鸭子.

AFAIK there is no special preconditions that can be checked, nor any ABC that object can be checked against in case of pickling. So all that is left is duck.

也许可以尝试其他方法,但可能不值得.很难对对象进行手动自省以初步了解它是否适​​合酸洗.

Maybe something else could be attempted but probably it is not worth of it. It would be very hard to do manual introspection of the object to find out preliminarily if it's suitable for pickling.

这篇关于如何检查物体是否可腌制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆