TypeError: cannot deepcopy this pattern object

Marcus Jones picture Marcus Jones · Jun 8, 2011 · Viewed 10k times · Source

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)

Answer

sth picture sth · Jun 8, 2011

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)