Search code examples
pythonpython-2.7monkeypatching

How to make deep copy of Python class?


I'd like to make a copy of class, while updating all of its methods to refer a new set of __globals__

I was thinking something like below, however unlike types.FunctionType, the constructor for types.UnboundMethodType does not accept __globals__, any suggestions how to work around this?

def copy_class(old_class, new_module):
  """Copies a class, updating __globals__ of all methods to point to new_module"""

  new_dict = {}
  for name, entry in old_class.__dict__.items():
    if isinstance(entry, types.UnboundMethodType):
      entry = types.UnboundMethodType(name, None, old_class.__class__, globals=new_module.__dict__)
    new_dict[name] = entry
  return type(old_class.name, old_class.__bases__, new_dict)

Solution

  • The __dict__ values are functions, not unbound methods. The unbound method objects only get created on attribute access. If you are seeing unbound method objects in the __dict__, something weird happened with your class object before this function got to it.