Skip to content

Instantly share code, notes, and snippets.

@naufraghi
Created August 12, 2011 15:33
Show Gist options
  • Save naufraghi/1142297 to your computer and use it in GitHub Desktop.
Save naufraghi/1142297 to your computer and use it in GitHub Desktop.
Given a method return all the classes the method is implemented in
def find_implementing_classes(method):
"""
Given a method return all the classes the method is implemented in.
a.aaa() -> A.aaa
a.bbb() -> A.bbb
b.aaa() -> A.aaa
b.bbb() -> B.bbb
A.aaa == B.aaa -> True
A.bbb == B.bbb -> False
find_implementing_classes(b.aaa) -> [<class '__main__.A'>]
find_implementing_classes(b.bbb) -> [<class '__main__.B'>, <class '__main__.A'>]
"""
mro = method.im_class.__mro__
func_name = method.im_func.func_name
impls = {}
for i, cls in enumerate(mro):
if hasattr(cls, func_name):
impls[getattr(cls, func_name)] = (i, cls)
return tuple(x[1] for x in sorted(impls.values()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment