Skip to content

Instantly share code, notes, and snippets.

@TySkby
Created June 15, 2017 19:17
Show Gist options
  • Save TySkby/fd45d15de4c249830bb04df69b297116 to your computer and use it in GitHub Desktop.
Save TySkby/fd45d15de4c249830bb04df69b297116 to your computer and use it in GitHub Desktop.
Build class hierarchies (and print them)
"""Utilities to build and view class hierarchy represntations in Python"""
def build_class_hierarchy(base_class, dot_paths=False):
"""
Given any (base) class, produces a nested dictionary
representation of the hierarchy formed by all descendents
of the class, with the given `base_class` forming the root
of the hierarchy.
:param base_class: The parent-most class on which the
hierarchy will be based
:type base_class: type
:param dot_paths: (Optional) If False, uses the class name
to represent classes in the hierarchy. If True, uses
the full, dot-notated Python module path as a prefix
to the class name. Defaults to False.
:type dot_paths: bool
:return: A dictionary representation of the descendent hierarchy
for the provided `base_class`, starting with that class.
:rtype: dict
"""
if dot_paths:
class_name = '{}.{}'.format(base_class.__module__, base_class.__name__)
else:
class_name = base_class.__name__
hierarchy = {class_name: {}}
for subclass in base_class.__subclasses__():
hierarchy[class_name].update(
build_class_hierarchy(subclass, dot_paths)
)
return hierarchy
def format_class_hierarchy(hierarchy, indent=0):
"""
Given a dict representation of a class hierarchy,
build a string which can be used to print a visual
representation of the hierarchy.
:param hierarcy: A dict representation of a hierarchy,
likely produced by :func:`build_class_hierarchy`
:type hierarchy: dict
:indent: The starting indentation (hierarchy) level,
which generally need not provided by users.
Should be a value >= 0.
:indent: int
:return: A string providing a printable representation of the hierarchy
:rtype: str
"""
output = ''
for k in sorted(hierarchy.keys()):
line = '{spaces}{dashes} {name}\n'.format(
spaces=' ' * (indent * 2),
dashes='-' * (indent + 1),
name=k
)
output += line
if hierarchy[k]:
output += format_class_hierarchy(hierarchy[k], indent + 1)
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment