Python Glossary Русский

all Python 3astterm

ast.ExceptHandler

control flow

The node of one except clause: the exception type in type, the as name in name and the body. Clauses sit in the handlers list of a Try or TryStar node.

Syntax

ast.ExceptHandler(type=None, name=None, body)

name is a string or None, not a Name node, so a variable search through visit_Name will not find it. A bare except: gives type=None — this is how linters catch a swallow-everything handler. except (A, B) stores a Tuple node in type, and the classes have to be pulled from its elts. except* clauses in 3.11+ are ExceptHandler too, but live in TryStar.

Examples

import ast
src = 'try:\n    pass\nexcept (KeyError, ValueError) as e:\n    pass\nexcept:\n    pass'
first, bare = ast.parse(src).body[0].handlers
print(type(first.type).__name__, repr(first.name))  # → Tuple 'e'
print([el.id for el in first.type.elts])  # → ['KeyError', 'ValueError']
print(bare.type, bare.name)  # → None None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy