ruff/crates/red_knot_python_semantic/resources/mdtest/exception/basic.md
Carl Meyer a48d779c4e
[red-knot] function signature representation (#14304)
## Summary

Add a typed representation of function signatures (parameters and return
type) and infer it correctly from a function.

Convert existing usage of function return types to use the signature
representation.

This does not yet add inferred types for parameters within function body
scopes based on the annotations, but it should be easy to add as a next
step.

Part of #14161 and #13693.

## Test Plan

Added tests.
2024-11-14 23:34:24 +00:00

1.2 KiB

Exception Handling

Single Exception

import re

try:
    help()
except NameError as e:
    reveal_type(e)  # revealed: NameError
except re.error as f:
    reveal_type(f)  # revealed: error

Unknown type in except handler does not cause spurious diagnostic

from nonexistent_module import foo  # error: [unresolved-import]

try:
    help()
except foo as e:
    reveal_type(foo)  # revealed: Unknown
    reveal_type(e)  # revealed: Unknown

Multiple Exceptions in a Tuple

EXCEPTIONS = (AttributeError, TypeError)

try:
    help()
except (RuntimeError, OSError) as e:
    reveal_type(e)  # revealed: RuntimeError | OSError
except EXCEPTIONS as f:
    reveal_type(f)  # revealed: AttributeError | TypeError

Dynamic exception types

def foo(
    x: type[AttributeError],
    y: tuple[type[OSError], type[RuntimeError]],
    z: tuple[type[BaseException], ...],
):
    try:
        help()
    except x as e:
        # TODO: should be `AttributeError`
        reveal_type(e)  # revealed: @Todo
    except y as f:
        # TODO: should be `OSError | RuntimeError`
        reveal_type(f)  # revealed: @Todo
    except z as g:
        # TODO: should be `BaseException`
        reveal_type(g)  # revealed: @Todo