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

发布于 2024-11-14 14:27:11 字数 953 浏览 2 评论 0原文

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

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

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)

Trying to understand this error in my "Variable" class.

I was hoping to store a sre.SRE_Pattern in my "Variable" class. I just started copying the Variable class and noticed that it was causing all my Variable class instances to change. I now understand that I need to deepcopy this class, but now I run into "TypeError: cannot deepcopy this pattern object". Sure, I can store the pattern as a text string but the rest of my code already expects a compiled pattern! What would be the best way to copy my Variable class with a pattern object?

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

絕版丫頭 2024-11-21 14:27:11

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

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

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

deepcopy doesn't know anything about your classes and doesn't know how to copy them.

You can tell deepcopy how to copy your objects by implementing a __deepcopy__() method:

class VariableWithoutRE(object):
   # ...
   def __deepcopy__(self):
      return VariableWithoutRE(self.name, self.regexTarget, self.type)
━╋う一瞬間旳綻放 2024-11-21 14:27:11

这可以通过在 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

This can be worked around by patching copy module in pre-3.7 python:

import copy
import re 

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

o = re.compile('foo')
assert copy.deepcopy(o) == o
凉薄对峙 2024-11-21 14:27:11

这似乎在 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

This seems to be fixed in 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.)

as per: https://docs.python.org/3/whatsnew/3.7.html#re

Testing:

import re,copy

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

myobj = C()    
foo = copy.deepcopy(myobj)
foo.regex == myobj.regex
# True
陌路终见情 2024-11-21 14:27:11

问题似乎是编译的正则表达式。 deepcopy 无法处理它们。

一个最小的示例给了我同样的错误:

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

myobj = C()    
copy.deepcopy(myobj)

这会引发错误:TypeError:无法深度复制此模式对象。我在python3.5。

The problem seems to be the compiled regex. deepcopy cannot handle them.

A minimal example gives me the same error:

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

myobj = C()    
copy.deepcopy(myobj)

This throws the error: TypeError: cannot deepcopy this pattern object. I'm in python3.5.

泪是无色的血 2024-11-21 14:27:11

如果此类(及其子类_)的实例不需要需要深度复制,但只会导致问题,因为它们是做<的对象图的一部分/strong> 需要深复制,那么你可以这样做:

#might as well limit this hack to versions that need it...
if sys.version_info <= (3, 7):

    def __deepcopy__(self, *args, **kwargs):
        """ cheat here because regex can't be deepcopied"""
        return self

现在,你需要小心了。我所做的假设。如果您开始更改此类的任何实例,则可能会出现副作用,因为深层复制实际上并未发生。仅当您在其他地方需要深度复制并且您非常确定您不关心此类和深度复制时,才值得这样做。

IF your instances of this class (and its subclasses_) don't need deep-copy but are only causing problems because they are part of object graphs that do need deep-copy, then you could do this:

#might as well limit this hack to versions that need it...
if sys.version_info <= (3, 7):

    def __deepcopy__(self, *args, **kwargs):
        """ cheat here because regex can't be deepcopied"""
        return self

Now, you need to be careful re. the assumption I am making. If you start altering any instances of this class, you are at risk of having side effects appear because the deepcopy did not in fact take place. It's only worthwhile if you need deepcopy elsewhere and you are pretty sure you don't care about this class and deepcopy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文