Last active
December 30, 2016 00:15
-
-
Save h2non/bb0fe85a8fba519b29d88649e4d5b322 to your computer and use it in GitHub Desktop.
Python metaprogramming for the win! Simple function to check is a given class has a subclass in the subclasses hierarchy chain.
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 issubsubclass(cls, subcls): | |
""" | |
Recursively check if a given class has a subclass of `obj` class in the | |
subclasses hierarchy. | |
Under the hood, it does some metaprogramming magic recursively checking | |
the `__bases__` magic attribute. | |
Extends `issubclass` built-in function to check subclass hierarchies. | |
Arguments: | |
cls (class): class to check. | |
subcls (class): class to lookup in the classes hierarchy. | |
Returns: | |
bool: `True` if it's the subclass is found, otherwise `False`. | |
""" | |
if not cls: | |
return False | |
if issubclass(cls, subcls): | |
return True | |
if getattr(cls, '__bases__', None): | |
return issubsubclass(cls.__bases__[0], subcls) | |
return cls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment