2

Is there a way to monkey-patch core python class ? Something along the lines :

class Boo:
    def is_empty(self) : return not self

list.is_empty = Boo.is_empty

TypeError: can't set attributes of built-in/extension type 'list'

I don't want to extend it , I want to monkey-patch it.


Sorry I meant "monkey-patch".

sten
  • 7,028
  • 9
  • 41
  • 63

1 Answers1

3

If you mean monkey patching instead of duck typing, then yes, you can do it with ctypes as @juanpa.arrivillaga suggested in the comments: https://gist.github.com/mahmoudimus/295200

But even then I'd highly advice against it, since it can break everyone else's code if they import your module. Imagine what would happen if everyone started messing with the internals, you couldn't safely import anything anymore!

What you should do instead is subclass the Python classes:

class Boo(list):
    def is_empty(self):
        return not self

>>> my_list = Boo([1, 2, 3, 4, 5])
>>> my_list2 = Boo([])
>>> my_list.is_empty()
False
>>> my_list2.is_empty()
True
>>> my_list2.append(5)
>>> my_list2.is_empty()
False
>>> my_list2
[5]
Community
  • 1
  • 1
Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119