Python Glossary Русский

all Python 3inspectfunction

inspect.getclasstree()

classes and functions

Arranges a list of classes into an inheritance tree of nested lists: a (class, bases) tuple followed by a list of its subclasses.

Syntax

inspect.getclasstree(classes, unique=False)

The structure is not obvious: a node is a (class, tuple of bases) pair, and its children follow as the next element in a separate list, so you walk it recursively, checking isinstance(item, list). Bases missing from the input, such as object, are added as roots automatically. With multiple inheritance a class appears under every parent; unique=True keeps a single entry.

Examples

import inspect
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
def show(tree, depth=0):
    for item in tree:
        if isinstance(item, list):
            show(item, depth + 1)
        else:
            print('.' * depth + item[0].__name__)
show(inspect.getclasstree([A, B, C, D]))
# → object / .A / ..B / ...D / ..C / ...D
show(inspect.getclasstree([A, B, C, D], unique=True))
# → object / .A / ..B / ...D / ..C

See also

Open in the full glossarydocs.python.orgReport an inaccuracy