Skip to content

Instantly share code, notes, and snippets.

@Zulko
Created April 18, 2017 18:04
Show Gist options
  • Save Zulko/e0910cac1b27bcc3a1e6585eaee60121 to your computer and use it in GitHub Desktop.
Save Zulko/e0910cac1b27bcc3a1e6585eaee60121 to your computer and use it in GitHub Desktop.
Automatic Python module class tree generation, using Mermaid for rendering
import inspect
def class_name(cls):
"""Return a string representing the class"""
# NOTE: can be changed to str(class) for more complete class info
return cls.__name__
def classes_tree(module, base_module=None):
if base_module is None:
base_module == module.__name__
module_classes = set()
inheritances = []
def inspect_class(cls):
if class_name(cls) not in module_classes:
if cls.__module__.startswith(base_module):
module_classes.add(class_name(cls))
for base in cls.__bases__:
inheritances.append((class_name(base), class_name(cls)))
inspect_class(base)
for cls in [e for e in module.__dict__.values() if inspect.isclass(e)]:
inspect_class(cls)
return module_classes, inheritances
def classes_tree_to_mermaid(module_classes, inheritances):
return "graph TD;\n" + "\n".join(
list(module_classes) + [
"%s --> %s" % (a, b)
for a, b in inheritances
]
)
if __name__ == "__main__":
import moviepy.editor as mpe
module_classes, inheritances = classes_tree(mpe, base_module='moviepy')
print (classes_tree_to_mermaid(module_classes, inheritances))
"""
Result:
graph TD;
CompositeAudioClip
ColorClip
ImageSequenceClip
Clip
ImageClip
CompositeVideoClip
VideoFileClip
AudioClip
VideoClip
TextClip
AudioFileClip
VideoClip --> ImageSequenceClip
Clip --> VideoClip
VideoClip --> VideoFileClip
ImageClip --> ColorClip
VideoClip --> ImageClip
ImageClip --> TextClip
AudioClip --> CompositeAudioClip
Clip --> AudioClip
AudioClip --> AudioFileClip
VideoClip --> CompositeVideoClip
"""
@Zulko
Copy link
Author

Zulko commented Apr 18, 2017

Result image:

result image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment