Skip to content

Instantly share code, notes, and snippets.

@Mihitoko
Created June 2, 2022 15:59
Show Gist options
  • Select an option

  • Save Mihitoko/33cb89b08770d34d8b314e748877962d to your computer and use it in GitHub Desktop.

Select an option

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.
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