ruff/crates/red_knot_python_semantic/resources/mdtest/annotations/optional.md
Matthew Mckee 3a5f1d46c0
[red-knot] Make' Type::in_type_expression()' exhaustive for Type::KnownInstance (#16836)
<!--
Thank you for contributing to Ruff! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title?
- Does this pull request include references to any relevant issues?
-->

## Summary

fixes #15048 
We want to handle more types from Type::KnownInstance 

## Test Plan

Add tests for each type added explicitly in the match

---------

Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
2025-03-19 07:36:28 -07:00

981 B

Optional

Annotation

typing.Optional is equivalent to using the type with a None in a Union.

from typing import Optional

a: Optional[int]
a1: Optional[bool]
a2: Optional[Optional[bool]]
a3: Optional[None]

def f():
    # revealed: int | None
    reveal_type(a)
    # revealed: bool | None
    reveal_type(a1)
    # revealed: bool | None
    reveal_type(a2)
    # revealed: None
    reveal_type(a3)

Assignment

from typing import Optional

a: Optional[int] = 1
a = None
# error: [invalid-assignment] "Object of type `Literal[""]` is not assignable to `int | None`"
a = ""

Typing Extensions

from typing_extensions import Optional

a: Optional[int]

def f():
    # revealed: int | None
    reveal_type(a)

Invalid

from typing import Optional

# error: [invalid-type-form] "`typing.Optional` requires exactly one argument when used in a type expression"
def f(x: Optional) -> None:
    reveal_type(x)  # revealed: Unknown