ruff/crates/red_knot_python_semantic/resources/mdtest/expression/if.md
Dhruv Manilawala d082c1b202
[red-knot] Add missing imports in mdtests (#15869)
## Summary

Related to #15848, this PR adds the imports explicitly as we'll now flag
these symbols as undefined.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2025-02-03 09:27:29 +00:00

1,007 B

If expression

Union

def _(flag: bool):
    reveal_type(1 if flag else 2)  # revealed: Literal[1, 2]

Statically known conditions in if-expressions

reveal_type(1 if True else 2)  # revealed: Literal[1]
reveal_type(1 if "not empty" else 2)  # revealed: Literal[1]
reveal_type(1 if (1,) else 2)  # revealed: Literal[1]
reveal_type(1 if 1 else 2)  # revealed: Literal[1]

reveal_type(1 if False else 2)  # revealed: Literal[2]
reveal_type(1 if None else 2)  # revealed: Literal[2]
reveal_type(1 if "" else 2)  # revealed: Literal[2]
reveal_type(1 if 0 else 2)  # revealed: Literal[2]

Leaked Narrowing Constraint

(issue #14588)

The test inside an if expression should not affect code outside of the expression.

from typing import Literal

def _(flag: bool):
    x: Literal[42, "hello"] = 42 if flag else "hello"

    reveal_type(x)  # revealed: Literal[42, "hello"]

    _ = ... if isinstance(x, str) else ...

    reveal_type(x)  # revealed: Literal[42, "hello"]