是否可以腌制(使用 cPickle)已使用 Boost.Python 公开的枚举?我已经使用这里描述的第一种方法成功地腌制了其他对象,但是这些似乎都不适用于枚举类型,并且默认情况下这些对象似乎不是可腌制的。
问问题
1313 次
1 回答
6
不像他们在模块中那样。我了解到这是可能的,但 enum_ 语句的工作方式阻止了这一点。
你可以在 python 端解决这个问题。某处(可能在 __init__.py 文件中)执行以下操作:
import yourmodule
def isEnumType(o):
return isinstance(o, type) and issubclass(o,int) and not (o is int)
def _tuple2enum(enum, value):
enum = getattr(yourmodule, enum)
e = enum.values.get(value,None)
if e is None:
e = enum(value)
return e
def _registerEnumPicklers():
from copy_reg import constructor, pickle
def reduce_enum(e):
enum = type(e).__name__.split('.')[-1]
return ( _tuple2enum, ( enum, int(e) ) )
constructor( _tuple2enum)
for e in [ e for e in vars(yourmodule).itervalues() if isEnumType(e) ]:
pickle(e, reduce_enum)
_registerEnumPicklers()
这将使所有的泡菜都很好。
于 2010-10-20T18:20:25.470 回答