2009-09-06 58 views
5

如果一个Python 3类使用协议2腌制,它应该在Python 2的工作,但不幸的是,这种失败,因为一些类的名称已更改。取储存类在Python 3在Python 2

假设我们有如下所示的代码。

发件人

pickle.dumps(obj,2) 

接收机

pickle.loads(atom) 

为了给出具体情况下,如果obj={},然后给出的误差为:

ImportError: No module named builtins

这是因为Python 2使用__builtin__代替。

问题是解决此问题的最佳方法。

回答

13

此问题是Python issue 3675。这个bug实际上在Python 3.11中得到了修复。

如果我们导入:

from lib2to3.fixes.fix_imports import MAPPING 

MAPPING Python的2名映射到Python 3名。我们希望相反。

REVERSE_MAPPING={} 
for key,val in MAPPING.items(): 
    REVERSE_MAPPING[val]=key 

我们可以覆盖Unpickler会和负载

class Python_3_Unpickler(pickle.Unpickler): 
    """Class for pickling objects from Python 3""" 
    def find_class(self,module,name): 
     if module in REVERSE_MAPPING: 
      module=REVERSE_MAPPING[module] 
     __import__(module) 
     mod = sys.modules[module] 
     klass = getattr(mod, name) 
     return klass 

def loads(str): 
    file = pickle.StringIO(str) 
    return Python_3_Unpickler(file).load() 

然后我们把这种负载,而不是pickle.loads。

这应该解决的问题。