Skip to content

Instantly share code, notes, and snippets.

View Mihitoko's full-sized avatar

Maximilian Lotz Mihitoko

  • InnoGames
  • Germany Schleswig Holstein
View GitHub Profile
@Mihitoko
Mihitoko / hook.py
Created June 2, 2022 15:59
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.
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)