mirror of
https://github.com/astral-sh/ruff.git
synced 2026-11-21 20:29:20 +08:00
## 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.
8.2 KiB
8.2 KiB
Expressions
OR
def _(foo: str):
reveal_type(True or False) # revealed: Literal[True]
reveal_type("x" or "y" or "z") # revealed: Literal["x"]
reveal_type("" or "y" or "z") # revealed: Literal["y"]
reveal_type(False or "z") # revealed: Literal["z"]
reveal_type(False or True) # revealed: Literal[True]
reveal_type(False or False) # revealed: Literal[False]
reveal_type(foo or False) # revealed: (str & ~AlwaysFalsy) | Literal[False]
reveal_type(foo or True) # revealed: (str & ~AlwaysFalsy) | Literal[True]
AND
def _(foo: str):
reveal_type(True and False) # revealed: Literal[False]
reveal_type(False and True) # revealed: Literal[False]
reveal_type(foo and False) # revealed: (str & ~AlwaysTruthy) | Literal[False]
reveal_type(foo and True) # revealed: (str & ~AlwaysTruthy) | Literal[True]
reveal_type("x" and "y" and "z") # revealed: Literal["z"]
reveal_type("x" and "y" and "") # revealed: Literal[""]
reveal_type("" and "y") # revealed: Literal[""]
Simple function calls to bool
def _(flag: bool):
if flag:
x = True
else:
x = False
reveal_type(x) # revealed: bool
Complex
reveal_type("x" and "y" or "z") # revealed: Literal["y"]
reveal_type("x" or "y" and "z") # revealed: Literal["x"]
reveal_type("" and "y" or "z") # revealed: Literal["z"]
reveal_type("" or "y" and "z") # revealed: Literal["z"]
reveal_type("x" and "y" or "") # revealed: Literal["y"]
reveal_type("x" or "y" and "") # revealed: Literal["x"]
bool() function
Evaluates to builtin
a.py:
redefined_builtin_bool: type[bool] = bool
def my_bool(x) -> bool:
return True
from a import redefined_builtin_bool, my_bool
reveal_type(redefined_builtin_bool(0)) # revealed: Literal[False]
reveal_type(my_bool(0)) # revealed: bool
Truthy values
[environment]
python-version = "3.11"
import enum
from typing import Literal, final
reveal_type(bool(1)) # revealed: Literal[True]
reveal_type(bool((0,))) # revealed: Literal[True]
reveal_type(bool("NON EMPTY")) # revealed: Literal[True]
reveal_type(bool(True)) # revealed: Literal[True]
def foo(): ...
reveal_type(bool(foo)) # revealed: Literal[True]
class SingleElementTupleSubclass(tuple[int]): ...
reveal_type(bool(SingleElementTupleSubclass((0,)))) # revealed: Literal[True]
# Unknown length, but we know the length is guaranteed to be >=2
class MixedTupleSubclass(tuple[int, *tuple[str, ...], bytes]): ...
reveal_type(bool(MixedTupleSubclass((1, b"foo")))) # revealed: Literal[True]
# Unknown length with an overridden `__bool__`:
class VariadicTupleSubclassWithDunderBoolOverride(tuple[int, ...]):
def __bool__(self) -> Literal[True]:
return True
reveal_type(bool(VariadicTupleSubclassWithDunderBoolOverride((1,)))) # revealed: Literal[True]
# Same again but for a subclass of a fixed-length tuple:
class EmptyTupleSubclassWithDunderBoolOverride(tuple[()]):
# TODO: we should reject this override as a Liskov violation:
def __bool__(self) -> Literal[True]:
return True
reveal_type(bool(EmptyTupleSubclassWithDunderBoolOverride(()))) # revealed: Literal[True]
reveal_type(EmptyTupleSubclassWithDunderBoolOverride.__bool__) # revealed: def __bool__(self) -> Literal[True]
# revealed: bound method EmptyTupleSubclassWithDunderBoolOverride.__bool__() -> Literal[True]
reveal_type(EmptyTupleSubclassWithDunderBoolOverride().__bool__)
@final
class FinalClassOverridingLenAndNotBool:
def __len__(self) -> Literal[42]:
return 42
reveal_type(bool(FinalClassOverridingLenAndNotBool())) # revealed: Literal[True]
@final
class FinalClassWithNoLenOrBool: ...
reveal_type(bool(FinalClassWithNoLenOrBool())) # revealed: Literal[True]
class EnumWithMembers(enum.Enum):
A = 1
B = 2
reveal_type(bool(EnumWithMembers.A)) # revealed: Literal[True]
def f(x: SingleElementTupleSubclass | FinalClassOverridingLenAndNotBool | FinalClassWithNoLenOrBool | Literal[EnumWithMembers.A]):
reveal_type(bool(x)) # revealed: Literal[True]
Falsy values
import enum
from typing import final, Literal
reveal_type(bool(0)) # revealed: Literal[False]
reveal_type(bool(())) # revealed: Literal[False]
reveal_type(bool(None)) # revealed: Literal[False]
reveal_type(bool("")) # revealed: Literal[False]
reveal_type(bool(False)) # revealed: Literal[False]
reveal_type(bool()) # revealed: Literal[False]
class EmptyTupleSubclass(tuple[()]): ...
reveal_type(bool(EmptyTupleSubclass())) # revealed: Literal[False]
@final
class FinalClassOverridingLenAndNotBool:
def __len__(self) -> Literal[0]:
return 0
reveal_type(bool(FinalClassOverridingLenAndNotBool())) # revealed: Literal[False]
class EnumWithMembersOverridingBool(enum.Enum):
A = 1
B = 2
def __bool__(self) -> Literal[False]:
return False
reveal_type(bool(EnumWithMembersOverridingBool.A)) # revealed: Literal[False]
def f(x: EmptyTupleSubclass | FinalClassOverridingLenAndNotBool | Literal[EnumWithMembersOverridingBool.A]):
reveal_type(bool(x)) # revealed: Literal[False]
Ambiguous values
import enum
from typing import Literal
reveal_type(bool([])) # revealed: bool
reveal_type(bool({})) # revealed: bool
reveal_type(bool(set())) # revealed: bool
class VariadicTupleSubclass(tuple[int, ...]): ...
def f(x: tuple[int, ...], y: VariadicTupleSubclass):
reveal_type(bool(x)) # revealed: bool
class NonFinalOverridingLenAndNotBool:
def __len__(self) -> Literal[42]:
return 42
# We cannot consider `__len__` for a non-`@final` type,
# because a subclass might override `__bool__`,
# and `__bool__` takes precedence over `__len__`
reveal_type(bool(NonFinalOverridingLenAndNotBool())) # revealed: bool
class EnumWithMembersOverridingBool(enum.Enum):
A = 1
B = 2
def __bool__(self) -> bool:
return False
reveal_type(bool(EnumWithMembersOverridingBool.A)) # revealed: bool
__bool__ returning NoReturn
from typing import NoReturn
class NotBoolable:
def __bool__(self) -> NoReturn:
raise NotImplementedError("This object can't be converted to a boolean")
# TODO: This should emit an error that `NotBoolable` can't be converted to a bool but it currently doesn't
# because `Never` is assignable to `bool`. This probably requires dead code analysis to fix.
if NotBoolable():
pass
Not callable __bool__
class NotBoolable:
__bool__: None = None
# error: [unsupported-bool-conversion] "Boolean conversion is not supported for type `NotBoolable`"
if NotBoolable():
pass
Not-boolable union
def test(cond: bool):
class NotBoolable:
__bool__: int | None = None if cond else 3
# error: [unsupported-bool-conversion] "Boolean conversion is not supported for type `NotBoolable`"
if NotBoolable():
pass
Union with some variants implementing __bool__ incorrectly
from typing import Literal
class NotBoolable:
__bool__: None = None
def test(a: Literal[10] | NotBoolable):
# error: [unsupported-bool-conversion] "Boolean conversion is not supported for type `Literal[10] | NotBoolable`"
if a:
pass
Uninhabited operands
An operand of type Never cannot produce a value. Later operands contribute no result, but earlier
operands can still produce a result by short-circuiting before reaching it.
from typing_extensions import Never
def _(value: Never):
reveal_type(value and True) # revealed: Never
def _(value: Never):
reveal_type(value or False) # revealed: Never
def _(value: Never):
reveal_type(True and value) # revealed: Never
def _(value: Never):
reveal_type(False or value) # revealed: Never
def _(value: Never):
reveal_type(False and value) # revealed: Literal[False]
reveal_type(True or value) # revealed: Literal[True]
def _(value: Never, flag: bool):
reveal_type(flag and value) # revealed: Literal[False]
def _(value: Never, flag: bool):
reveal_type(flag or value) # revealed: Literal[True]
def _(value: Never, flag: bool):
reveal_type(flag and value and 1) # revealed: Literal[False]
def _(value: Never, flag: bool):
reveal_type(flag or value or 1) # revealed: Literal[True]