mirror of
https://github.com/astral-sh/ruff.git
synced 2026-11-25 11:31:16 +08:00
## Summary
Previously, we treated every definition inside a `try` block as a
possible exception point, allowing handlers to observe states that could
never occur:
```py
def may_raise(value: object) -> None: ...
state = 0
try:
may_raise(state := 1)
except:
reveal_type(state)
# Before: Literal[0, 1]
# After: Literal[1]
```
We now record exception checkpoints immediately before operations that
can raise, after evaluating their operands. This includes calls,
imports, name lookups, attribute access, operators, iteration, and other
potentially raising operations.
(This is based on Carl's draft: #27221.)
---------
Co-authored-by: Carl Meyer <carl@astral.sh>
469 B
469 B
Exception Handling
Invalid syntax
try:
print()
except as e: # error: [invalid-syntax]
reveal_type(e) # revealed: Unknown
Invalid handler syntax does not create an exception path
A syntax error in an exception handler does not make that handler reachable if the try block
cannot raise.
state = 0
try:
state = 1
except as e: # error: [invalid-syntax]
state = "unreachable"
reveal_type(state) # revealed: Literal[1]