Skip to content Skip to sidebar Skip to footer

Add A Decorator To Existing Builtin Class Method In Python

I've got a class which contains a number of lists where whenever something is added to one of the lists, I need to trigger a change to the instance's state. I've created a simple

Solution 1:

You cannot monkey-patch builtins, so subclassing is the only way (and actually better and cleaner IMHO). I'd go for something like this:

classCustomList(list):

  def__init__(self, parent_instance, *args, **kwargs):
    super(CustomList, self).__init__(*args, **kwargs)
    self.parent_instance = parent_instance

  defappend(self, item):
      self.parent_instance.added = Truesuper(CustomList, self).append(item)


classMyClass(object):
    added = Falsedef__init__(self):
        self.list = CustomList(self, [1,2,3])


c = MyClass()
print c.added  # False
c.list.append(4)
print c.added  # True

Solution 2:

Would this suit your needs?

classMyClass(object):
    added = Falsedef__init__(self):
        self.list = [1,2,3]

    defappend(self, obj):
        self.added = True
        self.list.append(obj)



cls = MyClass()
cls.append(4)
cls.added #true

It might be helpful to know what exactly you're trying to achieve.

Post a Comment for "Add A Decorator To Existing Builtin Class Method In Python"