Python 3.3+astterm
ast.Try
control flow
Node for try: body, a handlers list of ExceptHandler, orelse for the else branch and finalbody for the finally branch.
Syntax
ast.Try(body, handlers, orelse, finalbody)
Since Python 3.3 one node covers every form: try/finally without except is a Try with empty handlers, and the old TryExcept and TryFinally are gone. A construct with except* parses as TryStar instead, so a traversal that knows only Try misses it. The field order matches execution order: body, handlers on error, orelse without one, finalbody always.
Examples
import ast
t = ast.parse('try:\n f()\nfinally:\n g()').body[0]
print(type(t).__name__, t.handlers, len(t.finalbody)) # → Try [] 1
import ast
src = 'try:\n f()\nexcept ValueError:\n pass\nelse:\n ok()'
t = ast.parse(src).body[0]
print(t.handlers[0].type.id, len(t.orelse)) # → ValueError 1
See also
Open in the full glossarydocs.python.orgReport an inaccuracy