2010-07-09 34 views
5

醃製(使用cPickle)已經暴露與Boost.Python的枚舉可能嗎?我已經用here描述的第一種方法成功地醃製了其他對象,但似乎沒有一個適用於枚舉類型,並且對象默認情況下似乎不可用。醃製Boost.Python公開的枚舉

+0

+1我不知道如何做到這一點,但非常想! (目前我轉換的枚舉必須先醃到整數) – James 2010-07-31 13:29:25

回答

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() 

這會讓一切鹹菜就好了。

+1

我剛剛遇到了這個問題,在類範圍內定義的枚舉,爲python 2.7.3。我手動添加:pickle(my_module.my_class.my_enum,reduce_enum),它工作。我刪除了枚舉類型的自動檢測 - 頂層枚舉的酸洗似乎已被修復。 – 2014-09-05 21:12:51

+0

很高興知道。謝謝。我已經有好幾年沒有和英國石油一起工作過,所以我沒有最新的。 – 2014-09-07 01:33:42