clarete/forbiddenfruit

Possible simplification of patchable_builtin()

Closed this issue ยท 2 comments

Jongy commented

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.

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

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.