clarete / forbiddenfruit

Patch built-in python objects
https://clarete.li/forbiddenfruit/
GNU General Public License v3.0
826 stars 52 forks source link

Possible simplification of patchable_builtin() #52

Closed Jongy closed 3 years ago

Jongy commented 3 years ago

I recently needed to patch builtin methods. Didn't know of forbiddenfruit at first, so I searched & found some workaround, and later I found this cool project via this SO question.

To work around the dictproxy/mappingproxy "issue" without diving into ctypes and messing with raw objects, I used the nice gc.get_referents method, which (together with its counterpart gc.get_referrers) lets you "get your hands" on objects you might have not been able to reach otherwise. dictproxy/mappingproxy are 2 dummy objects holding only a single reference, to the underlying mapping. So int_dict = gc.get_referents(int.__dict__)[0] is enough. With this simpler patchable_builtin, tests pass:

def patchable_builtin(klass):
    import gc
    refs = gc.get_referents(klass.__dict__)
    assert len(refs) == 1
    return refs[0]

Works the same, but simpler, so nicer IMO. Can open a PR with this improvement if you'd like.

clarete commented 3 years ago

This is nice!! And does look way simpler than the ctypes alternative to get a hold of the dict. It'd be great if you wanted to put a lil PR up with the improvement. Thank you 🙇🏾

Jongy commented 3 years ago

This is nice!! And does look way simpler than the ctypes alternative to get a hold of the dict. It'd be great if you wanted to put a lil PR up with the improvement. Thank you 🙇🏾

Cool, I'll just run the tests on all relevant CPython versions, and submit it.