Created
June 2, 2022 15:59
-
-
Save Mihitoko/33cb89b08770d34d8b314e748877962d to your computer and use it in GitHub Desktop.
A small hook that can hook the __new__ function of class definitions to return a subclass instead. This is usefull if you want to subclass something that is created internaly by a library but you dont want to change source.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def hook_type(to_hook, new_cls: type): | |
| if to_hook not in new_cls.__mro__: | |
| raise TypeError(f"{new_cls} musst subclass {to_hook}") | |
| old_new = to_hook.__new__ | |
| def hook(_, *args, **kwargs) -> type: | |
| if hasattr(old_new, "__self__"): | |
| if old_new.__self__ is object: | |
| return old_new(new_cls) | |
| return old_new(new_cls, *args, **kwargs) | |
| to_hook.__new__ = hook |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment