简体   繁体   中英

Print the Python Exception/Error Hierarchy

Is the any command line option in python to print the Exception/Error Class hierarchy?

The output should be similar to http://docs.python.org/2/library/exceptions.html#exception-hierarchy

inspect module might help, specifically getclasstree() function:

Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list.

inspect.getclasstree(inspect.getmro(Exception))

Or, you can recursively go through __subclasses__() down by an inheritance tree, like this:

def classtree(cls, indent=0):
    print '.' * indent, cls.__name__
    for subcls in cls.__subclasses__():
        classtree(subcls, indent + 3)

classtree(BaseException)

prints:

 BaseException
... Exception
...... StandardError
......... TypeError
......... ImportError
............ ZipImportError
......... EnvironmentError
............ IOError
............... ItimerError
............ OSError
......... EOFError
......... RuntimeError
............ NotImplementedError
......... NameError
............ UnboundLocalError
......... AttributeError
......... SyntaxError
............ IndentationError
............... TabError
......... LookupError
............ IndexError
............ KeyError
............ CodecRegistryError
......... ValueError
............ UnicodeError
............... UnicodeEncodeError
............... UnicodeDecodeError
............... UnicodeTranslateError
......... AssertionError
......... ArithmeticError
............ FloatingPointError
............ OverflowError
............ ZeroDivisionError
......... SystemError
............ CodecRegistryError
......... ReferenceError
......... MemoryError
......... BufferError
...... StopIteration
...... Warning
......... UserWarning
......... DeprecationWarning
......... PendingDeprecationWarning
......... SyntaxWarning
......... RuntimeWarning
......... FutureWarning
......... ImportWarning
......... UnicodeWarning
......... BytesWarning
...... _OptionError
... GeneratorExit
... SystemExit
... KeyboardInterrupt

Reuse code from the standard library instead of rolling your own.

import inspect
import pydoc

def print_class_hierarchy(classes=()):
    td = pydoc.TextDoc()
    tree_list_of_lists = inspect.getclasstree(classes)
    print(td.formattree(tree_list_of_lists, 'NameSpaceName'))

To use this, we need a hierarchy of classes, in the form of a list, that makes sense for us to pass our function. We can build this by recursively searching a classes .__subclasses__() method results, using this function ( which I'll keep the canonical version of here ):

def get_subclasses(cls):
    """returns all subclasses of argument, cls"""
    if issubclass(cls, type): # not a bound method
        subclasses = cls.__subclasses__(cls)
    else:
        subclasses = cls.__subclasses__()
    for subclass in subclasses:
        subclasses.extend(get_subclasses(subclass))
    return subclasses

Put this together:

list_of_classes = get_subclasses(int)
print_class_hierarchy(list_of_classes)

Which prints (in Python 3):

>>> print_class_hierarchy(classes)
builtins.int(builtins.object)
    builtins.bool
    enum.IntEnum(builtins.int, enum.Enum)
        inspect._ParameterKind
        signal.Handlers
        signal.Signals
    enum.IntFlag(builtins.int, enum.Flag)
        re.RegexFlag
    sre_constants._NamedIntConstant
    subprocess.Handle
enum.Enum(builtins.object)
    enum.IntEnum(builtins.int, enum.Enum)
        inspect._ParameterKind
        signal.Handlers
        signal.Signals
enum.Flag(enum.Enum)
    enum.IntFlag(builtins.int, enum.Flag)
        re.RegexFlag

This gives us a tree of all subclasses, as well as related multiple inheritance classes - and tells us the modules they live in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM