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:

class CustomList(list):

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

  def append(self, item):
      self.parent_instance.added = True
      super(CustomList, self).append(item)


class MyClass(object):
    added = False

    def __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?

class MyClass(object):
    added = False

    def __init__(self):
        self.list = [1,2,3]

    def append(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"