mermaidmro#

Build status Package version Python version Documentation status Code coverge License

Create mermaid graphs from the method resolution order (mro) of Python objects.

CLI Examples#

For the examples below, let’s consider the following classes saved in a file code.py that can be imported via import code (adjust your PYTHONPATH if this is not the case).

# code.py

class A(object):
    pass

class B(object):
    pass

class C(A):
    pass

class D(C, B):
    pass

Generate mermaid text#

Simply pass the module and class in the format module_name:class_name to mermaidmro.

> mermaidmro code:D

graph TD
    code.D("code.D (0)")
    code.C("code.C (1)")
    code.A("code.A (2)")
    code.B("code.B (3)")
    object("object (4)")

    code.C --> code.D
    code.B --> code.D
    code.A --> code.C
    object --> code.B
    object --> code.A

You can hide the mro indices by adding --no-mro / -n.

> mermaidmro code:D --no-mro

graph TD
    code.C --> code.D
    code.B --> code.D
    code.A --> code.C
    object --> code.B
    object --> code.A

You can also limit the maximum depth via --max-depth / -m.

> mermaidmro code:D --no-mro --max-depth 1

graph TD
    code.A --> code.D
    code.B --> code.D

Open the graph in your browser#

Just configure the executable of your browser you like to open the graph with via --cmd / -c (on Macs this is usually just open). This functionality is based on the mermaid.live service.

> mermaidmro code:D --cmd open

# opens https://mermaid.ink/img/pako:eNptkM8KwjAMh18l5JSBE_-dPAht9wgec6lbdYrdZNTT2LvbUUvLWE6_fB8kISPWfWPwDPgY9KeFa8Ud-JrptiLGEIB2BWORORWdAtovnIhOAB0WTkYngY7J9beXqZ13IQCdgss3Qlle_oflA9exSFjlKxKW61jgBtCawepnM_9lZHStsYZ9w9iYu_6-HeOE0w_Nr1i5?type=png

To open the graph in the live editor, add --edit.

Visualize the graph in your terminal#

This requires that you have a tool installed that lets you visualize images in your terminal, e.g. imgcat for iTerm2.

> mermaidmro code:D --visualize imgcat

# shows

code:D graph

Download the graph#

> mermaidmro code:D --download graph.png

Installation#

Simply install via pip

pip install mermaidmro

Development#

If you like to contribute, I’m happy to receive pull requests. Just make sure to add a new test cases and run linting and coverage checks:

> ./tests/test.sh
> ./tests/lint.sh
> ./tests/coverage.sh

API#

Functions#

get_mermaid_text(root_cls, max_depth=-1, styles=None, show_mro=True, graph_type='TD', arrow_type='-->', indentation='    ', skip_func=None, name_func=None, skip_modules=None, join_lines=True)[source]#

Creates a text representation of the inheritance graph for a root_cls, down to a maximum recursion depth max_depth. When styles is given, the representation contains style statements generated via get_style_text(). When show_mro is True, mro indices with respect to root_cls are shown. The type of the graph and style of arrows can be controlled with graph_type and arrow_type. Example:

class A(object): pass
class B(object): pass
class C(A): pass
class D(C, B): pass

get_mermaid_text(D)
# graph TD
#     D("D (0)")
#     C("C (1)")
#     A("A (2)")
#     B("B (3)")
#     object("object (4)")
#
#     C --> D
#     B --> D
#     A --> C
#     object --> A
#     object --> B

get_mermaid_text(D, show_mro=False)
# graph TD
#     C --> D
#     B --> D
#     A --> C
#     object --> A
#     object --> B
Parameters:
  • root_cls (type) – The root class to use.

  • max_depth (int) – Maximum recursion depth for the lookup in get_relations().

  • styles (list[Style | tuple] | None) – Sequence of Style objects or tuples that can be interpreted as such.

  • show_mro (bool) – Whether mro indices should be included.

  • graph_type (str) – The mermaid graph type to use, e.g. "TD" or "LR".

  • arrow_type (str) – The default arrow type to use between classes, e.g. "-->".

  • indentation (str) – The indentation of lines.

  • skip_func (Callable[[type, Callable], bool] | None) – A function to decide whether a specific base class should be skipped given the class itself and the name_func as arguments.

  • name_func (Callable[[type], str] | None) – A function to extract the string representation of a class, defaulting to the return value of get_default_name_func() passing skip_modules.

  • skip_modules (list[str] | set[str] | None) – Sequence of module names (or patterns) to skip when no name_func is set.

  • join_lines (bool) – Whether generated lines should be joined to a string.

Return type:

str | list[str]

Returns:

The style as a text representation or as single lines in a list.

get_style_text(styles, indentation='    ', name_func=None, skip_modules=None, join_lines=True)[source]#

Creates the string representation of style statements for mermaid graphs consisting of style definitions followed by assignments to graph nodes. styles should be a sequence of Style objects (or tuples that can be interpreted as such) containing the name of the style, the name(s) of the class(es) it is applied to, and one or multiple css-like strings, e.g. "stroke-width: 3px". Example:

get_style_text([
    Style(name="Bold", cls=["ClassA", "ClassB"], css=["stroke-width: 3px"]),
    Style(name="Colored", cls="ClassA", css=["stroke-width: 3px", "stroke: #83b"]),
])

#    classDef Bold stroke-width: 3px
#    classDef Colored stroke-width: 3px, stroke: #83b
#
#    class ClassA Bold
#    class ClassB Bold
#    class ClassA Colored
Parameters:
  • styles (list[Style | tuple]) – Sequence of Style objects or tuples that can be interpreted as such.

  • indentation (str) – The indentation of lines.

  • name_func (Callable[[type], str] | None) – A function to extract the string representation of a class, defaulting to the return value of get_default_name_func() passing skip_modules.

  • skip_modules (list[str] | set[str] | None) – Sequence of module names (or patterns) to skip when no name_func is set.

  • join_lines (bool) – Whether generated lines should be joined to a string.

Return type:

str | list[str]

Returns:

The style as a text representation or as single lines in a list.

get_relations(root_cls, max_depth=-1)[source]#

Recursively extracts base classes of a root_cls down to a maximum depth max_depth and returns them in a list of Relation objects. When max_depth is negative, the lookup is fully recursive, possibly down to object.

Parameters:
  • root_cls (type) – The root class to use.

  • max_depth (int) – Maximum recursion depth.

Return type:

list[Relation]

Returns:

The list of found Relation objects.

encode_text(mermaid_text)[source]#

Returns a base64 encoded variant of a mermaid graph given in mermaid_text, that is usually used in static urls of the mermaidjs service.

Parameters:

mermaid_text (str) – The graph as a string representation.

Return type:

str

Returns:

The base64 encoded representation of the text.

encode_json(mermaid_text, theme='default')[source]#

Returns a base64 encoded and compressed variant of a mermaid graph given in mermaid_text and additional configuration options such as theme, that is usually used in urls of the mermaidjs live editing service.

The structured data that is compressed has the format

{
    "code": "graph TD\n....",
    "mermaid": "{\"theme\": ...}"
}

as expected by mermaidjs.

Parameters:
  • mermaid_text (str) – The graph as a string representation.

  • theme (str | None) – Name of the theme to use.

Return type:

str

Returns:

The base64 encoded and compressed representation of the structured data containing the graph and configuration options.

download_graph(mermaid_text, path, file_type='jpg', theme='default')[source]#

Downloads a mermaid graph represented by mermaid_text from the mermaidjs service to a path in a specific file_type. Missing intermediate directories are created first.

Parameters:
  • mermaid_text (str) – The graph as a string representation.

  • path (str) – The path where the downloaded file should be saved.

  • file_type (str) – The file type to write, usually "jpg" or "png".

  • theme (str | None) – Name of the theme to use.

Return type:

str

Returns:

The absolute, normalized and expanded path.

get_default_name_func(skip_modules=None)[source]#

Returns a function that takes an arbitrary class and extracts its name representation, usually in the format "module_name.class_name". skip_modules can be a sequence of modules names of patterns matching module names that are not preprended. Please note that builtins and __main__ are always skipped.

Parameters:

skip_modules (list[str] | set[str] | None) – Optional squence of module names (or patterns) to skip.

Return type:

Callable[[type], str]

Returns:

Function that takes a class and returns the name for visualization.

Classes#

class Relation(cls, base_cls, root_cls, depth, mro)#

Relation between two classes including a depth value and the mro index with respect to the requested root class (namedtuple).

class Style(name, cls, css)#

Container object with attributes to define css styles for one or multiple classes (namedtuple).