类型错误:无法深入复制此模式对象

2024-09-30 23:41:39 发布

您现在位置:Python中文网/ 问答频道 /正文

试图在我的“变量”类中理解这个错误。

我希望在我的“Variable”类中存储sre.sre_模式。我刚开始复制Variable类,注意到它导致了我所有的Variable类实例的更改。我现在知道我需要deepcopy这个类,但是现在我遇到了“TypeError:cannotdeepcopythispatterobject”。当然,我可以将该模式存储为文本字符串,但我的其余代码已经需要编译的模式!用模式对象复制变量类的最佳方法是什么?

import re
from copy import deepcopy

class VariableWithRE(object):
    "general variable class"
    def __init__(self,name,regexTarget,type):
        self.name = name
        self.regexTarget = re.compile(regexTarget, re.U|re.M) 
        self.type = type 

class VariableWithoutRE(object):
    "general variable class"
    def __init__(self,name,regexTarget,type):
        self.name = name
        self.regexTarget = regexTarget
        self.type = type 

if __name__ == "__main__":

    myVariable = VariableWithoutRE("myName","myRegexSearch","myType")
    myVariableCopy = deepcopy(myVariable)

    myVariable = VariableWithRE("myName","myRegexSearch","myType")
    myVariableCopy = deepcopy(myVariable)

Tags: nameimportselfreobjecttype模式variable
3条回答

deepcopy对类一无所知,也不知道如何复制它们。

通过实现__deepcopy__()方法,您可以告诉deepcopy如何复制对象:

class VariableWithoutRE(object):
   # ...
   def __deepcopy__(self):
      return VariableWithoutRE(self.name, self.regexTarget, self.type)

在Python version 3.7+中似乎已经修复了这个问题:

Compiled regular expression and match objects can now be copied using copy.copy() and copy.deepcopy(). (Contributed by Serhiy Storchaka in bpo-10076.)

依据:https://docs.python.org/3/whatsnew/3.7.html#re

测试:

import re,copy

class C():
    def __init__(self):
       self.regex=re.compile('\d+')

myobj = C()    
foo = copy.deepcopy(myobj)
foo.regex == myobj.regex
# True

这可以通过修补3.7版python中的copy模块来解决:

import copy
import re 

copy._deepcopy_dispatch[type(re.compile(''))] = lambda r, _: r

o = re.compile('foo')
assert copy.deepcopy(o) == o

相关问题 更多 >