I would like to list Python lists for monkey patches, in particular, replace the __setitem__ method with custom code. Please note that I am not trying to extend, but overwrite, the built-in types. For instance:
>>>
Yes, I know this is just a perverse thing to do for python code. No, my usecase doesn't really make sense. However, can this be done?
Possible ways:
Case study
I really manage to override the methods themselves, as shown below:
import ctypes def magic_get_dict(o):
Which outputs the following:
➤ python3 override.py <slot wrapper '__setitem__' of 'list' objects> <function <lambda> at 0x10de43f28> <bound method <lambda> of [1, 2, 3, 4, 5]> [1, 20, 3, 4, 5]
But, as shown in the output, this does not seem to affect the normal syntax for setting the element ( x[0] = 0 )
Alternative: Monkey correcting an instance of a separate list
As a smaller alternative, if I could decapitate a separate copy of the list, this might work too. Perhaps by changing the pointer to the class in the user class.
source share