You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中清晰展示内置异常层级结构?

Visualizing Python's Built-in Exception Hierarchy & Finding Subclasses

Got it, let's break down how to properly visualize Python's built-in exception hierarchy (since dir(__builtins__) only gives you an alphabetical list with no inheritance context) and how to find all subclasses for any exception class.

1. Display the Full Exception Hierarchy

Since BaseException is the root of all Python exceptions, we can build a recursive function to traverse its subclass tree and print them with indentation to clearly show the hierarchy:

def print_exception_hierarchy(cls, indent=0):
    # Print the current class with indentation matching its depth in the hierarchy
    print('  ' * indent + cls.__name__)
    # Recursively print all subclasses, sorted by name for readability
    for subclass in sorted(cls.__subclasses__(), key=lambda x: x.__name__):
        print_exception_hierarchy(subclass, indent + 1)

# Start traversal from the root exception class
print_exception_hierarchy(BaseException)

When you run this, you'll get a clean, indented tree showing exactly how exceptions inherit from each other. For example, you'll see Exception as a direct subclass of BaseException, then ArithmeticError under Exception, followed by ZeroDivisionError under ArithmeticError, and so on.

2. Find All Subclasses of a Specific Exception Class

If you want to get all subclasses (including indirect ones) for a given exception class, use a recursive function to collect them:

Option 1: If you have the class object directly

def get_all_subclasses(cls):
    subclasses = set()
    # Get direct subclasses first
    for subclass in cls.__subclasses__():
        subclasses.add(subclass)
        # Recursively add indirect subclasses
        subclasses.update(get_all_subclasses(subclass))
    return subclasses

# Example: Get all subclasses of Exception
all_exception_subclasses = get_all_subclasses(Exception)
# Print them sorted by name
for cls in sorted(all_exception_subclasses, key=lambda x: x.__name__):
    print(cls.__name__)

Option 2: If you only have the class name as a string

First fetch the class from __builtins__, then use the same function:

class_name = "ValueError"
# Get the class object from built-ins
target_class = getattr(__builtins__, class_name)
# Get all its subclasses
all_subclasses = get_all_subclasses(target_class)
# Print results sorted by name
for cls in sorted(all_subclasses, key=lambda x: x.__name__):
    print(cls.__name__)

Bonus: Check the Inheritance Chain for a Single Class

If you want to see the exact inheritance path for a specific exception (from the class up to BaseException), use inspect.getmro() (method resolution order):

import inspect
# Show the inheritance chain for ValueError
print(inspect.getmro(ValueError))
# Output: (ValueError, Exception, BaseException, object)

This tells you exactly which classes ValueError inherits from, top to bottom.

内容的提问来源于stack exchange,提问作者Billal BEGUERADJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:03:40