Python Glossary Русский

all Python 3astterm

ast.excepthandler

control flow

The abstract base class of exception handlers; its only subclass is ExceptHandler. The handlers list of Try and TryStar consists of them.

Syntax

isinstance(h, ast.excepthandler)

Unlike many helper nodes, handlers do carry lineno and col_offset positions. A bare except: gives an ExceptHandler with type=None, which is how a linter spots catch-everything handlers. The name field is a string (the name after as) or None, not a Name node.

Examples

import ast
src = 'try:\n    f()\nexcept ValueError as e:\n    pass\nexcept:\n    pass'
for h in ast.parse(src).body[0].handlers:
    kind = ast.unparse(h.type) if h.type else None
    print(type(h).__name__, kind, h.name, h.lineno)
# → ExceptHandler ValueError e 3 / ExceptHandler None None 5

See also

Open in the full glossarydocs.python.orgReport an inaccuracy