Created
April 22, 2022 20:55
-
-
Save alexcmgit/caedf3e9dc5f02e06998645dbff61dbc to your computer and use it in GitHub Desktop.
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 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