Files
ruff/crates/red_knot_python_semantic/resources/mdtest/assignment/annotations.md
Charlie Marsh 6f52d573ef Support inference for PEP 604 union annotations (#13964)
## Summary

Supports return type inference for, e.g., `def f() -> int | None:`.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2024-10-28 10:13:01 -04:00

777 B

Assignment with annotations

Annotation only transparent to local inference

x = 1
x: int
y = x

reveal_type(y)  # revealed: Literal[1]

Violates own annotation

x: int = "foo"  # error: [invalid-assignment] "Object of type `Literal["foo"]` is not assignable to `int`"

Violates previous annotation

x: int
x = "foo"  # error: [invalid-assignment] "Object of type `Literal["foo"]` is not assignable to `int`"

PEP-604 annotations are supported

def foo() -> str | int | None:
    return None

reveal_type(foo())  # revealed: str | int | None

def bar() -> str | str | None:
    return None

reveal_type(bar())  # revealed: str | None

def baz() -> str | str:
    return "Hello, world!"

reveal_type(baz())  # revealed: str