Skip to content

Instantly share code, notes, and snippets.

@h2non
Last active December 30, 2016 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h2non/bb0fe85a8fba519b29d88649e4d5b322 to your computer and use it in GitHub Desktop.
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.
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