How to list python list for monkeys __setitem__

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:

 >>> # Monkey Patch ... # Replace list.__setitem__ with a Noop ... >>> myList = [1,2,3,4,5] >>> myList[0] = "Nope" >>> myList [1, 2, 3, 4, 5] 

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): # find address of dict whose offset is stored in the type dict_addr = id(o) + type(o).__dictoffset__ # retrieve the dict object itself dict_ptr = ctypes.cast(dict_addr, ctypes.POINTER(ctypes.py_object)) return dict_ptr.contents.value def magic_flush_mro_cache(): ctypes.PyDLL(None).PyType_Modified(ctypes.cast(id(object), ctypes.py_object)) print(list.__setitem__) dct = magic_get_dict(list) dct['__setitem__'] = lambda s, k, v: s magic_flush_mro_cache() print(list.__setitem__) x = [1,2,3,4,5] print(x.__setitem__) x.__setitem__(0,10) x[1] = 20 print(x) 

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.

+5
source share
1 answer

Unable to execute. If you really use CTypes, you'll just make Python run time faster than anything else, since many things only use Python data types.

0
source

All Articles