Print the Python Exception/Error Hierarchy

后端 未结 2 1090
不思量自难忘°
不思量自难忘° 2020-12-09 05:39

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.ht

相关标签:
2条回答
  • 2020-12-09 05:45

    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.

    0 讨论(0)
  • 2020-12-09 06:00

    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
    
    0 讨论(0)
提交回复
热议问题