Files
Charlie Marsh 3ac6b4c312 [ty] Represent uninhabited truthiness explicitly (#28843)
## Summary

We now mark both branches of a condition with type `Never` as
unreachable:

```python
from typing import Never

def f(value: Never):
    if value:
        result = 1  # Unreachable.
    else:
        result = 2  # Also unreachable.
```

Previously, we treated `Never` as having ambiguous truthiness, allowing
either assignment to affect inference. In the reported loop, the
variables depend on each other, so including these impossible
assignments made their inferred types depend on which file we checked
first.

We add `Truthiness::Uninhabited` to represent the absence of either
boolean outcome. `Type::bool` and `Type::try_bool` return this variant
for `Never`, replacing the opt-in `bool_if_inhabited` API and making
callers handle the distinction explicitly.

Closes https://github.com/astral-sh/ty/issues/4577.
2026-10-08 20:46:56 -04:00

1.6 KiB

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]
# error: [redundant-condition] "always truthy"
reveal_type(1 if "not empty" else 2)  # revealed: Literal[1]
# error: [redundant-condition] "always truthy"
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]
# error: [redundant-condition] "always falsy"
reveal_type(1 if "" else 2)  # revealed: Literal[2]
reveal_type(1 if 0 else 2)  # revealed: Literal[2]

Conditions with uninhabited operands

Only paths that finish evaluating the condition contribute a result. A call with an uninhabited argument can be bypassed by short-circuiting, even when the call itself has type bool.

from typing_extensions import Never

def _(never: Never):
    reveal_type(1 if never else 2)  # revealed: Never

def _(flag: bool, never: Never):
    reveal_type(1 if flag or bool(never) else 2)  # revealed: Literal[1]
    reveal_type(1 if flag and bool(never) 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"]