Skip to content

Instantly share code, notes, and snippets.

@alexcmgit
Created April 22, 2022 20:55
Show Gist options
  • Save alexcmgit/caedf3e9dc5f02e06998645dbff61dbc to your computer and use it in GitHub Desktop.
Save alexcmgit/caedf3e9dc5f02e06998645dbff61dbc to your computer and use it in GitHub Desktop.
def get_class_that_defined_method(meth):
import functools, inspect
if isinstance(meth, functools.partial):
return get_class_that_defined_method(meth.func)
if inspect.ismethod(meth) or (inspect.isbuiltin(meth) and getattr(meth, '__self__', None) is not None and getattr(meth.__self__, '__class__', None)):
for cls in inspect.getmro(meth.__self__.__class__):
if meth.__name__ in cls.__dict__:
return cls
meth = getattr(meth, '__func__', meth) # fallback to __qualname__ parsing
if inspect.isfunction(meth):
cls = getattr(inspect.getmodule(meth),
meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0],
None)
if isinstance(cls, type):
return cls
return getattr(meth, '__objclass__', None) # handle special descriptor objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment