TypeError:无法深入复制此模式对象

Mar*_*nes 15 python regex deep-copy

试图在我的"变量"类中理解这个错误.

我希望在我的"变量"类中存储一个sre.SRE_Pattern.我刚刚开始复制Variable类,并注意到它导致我的所有Variable类实例都发生了变化.我现在明白我需要对这个类进行深度复制,但现在我遇到了"TypeError:无法深度复制这个模式对象".当然,我可以将模式存储为文本字符串,但我的其余代码已经预期编译模式!使用模式对象复制Variable类的最佳方法是什么?

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)
Run Code Online (Sandbox Code Playgroud)

sth*_*sth 10

deepcopy 我们对您的课程一无所知,也不知道如何复制它们.

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

class VariableWithoutRE(object):
   # ...
   def __deepcopy__(self):
      return VariableWithoutRE(self.name, self.regexTarget, self.type)
Run Code Online (Sandbox Code Playgroud)

  • @ user789215问题是你正在使用已经编译的正则表达式(self.regexTarget)调用``VariableWithoutRE``构造函数(__init__),而构造函数需要一个字符串. (2认同)

Gra*_*rus 5

这似乎在 Python 3.7+ 版本中得到修复:

现在可以使用 copy.copy() 和 copy.deepcopy() 复制已编译的正则表达式和匹配对象。(由 Serhiy Storchaka 在 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
Run Code Online (Sandbox Code Playgroud)


Ada*_*ski 5

这可以通过在copy3.7 之前的 python 中修补模块来解决:

import copy
import re 

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

o = re.compile('foo')
assert copy.deepcopy(o) == o
Run Code Online (Sandbox Code Playgroud)