Created
August 12, 2011 15:33
-
-
Save naufraghi/1142297 to your computer and use it in GitHub Desktop.
Given a method return all the classes the method is implemented in
This file contains 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 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