mirror of
https://github.com/astral-sh/ruff.git
synced 2026-11-22 11:09:19 +08:00
## Summary Use an unambiguously incompatible `list[str]` declaration in the loop-declaration regression. The earlier binding remains `list[int]`, while the loop assignment now matches the declared type, so the test isolates the incompatible pre-loop binding. The previous `list[object]` declaration could become valid under whole-scope bidirectional inference, making it an ambiguous example for this diagnostic. Follow-up to [review feedback on #27594](https://github.com/astral-sh/ruff/pull/27594#discussion_r3753906101).
1.9 KiB
1.9 KiB
Errors while declaring
Violates previous assignment
x = 1
x: str # error: [invalid-declaration] "Cannot declare type `str` for inferred type `Literal[1]`"
Declarations in loops reject incompatible earlier bindings
An incompatible binding that predates the loop must still invalidate a declaration inside it.
values = [1]
while True:
values: list[str] # error: [invalid-declaration]
values = ["a"]
Incompatible declarations
def _(flag: bool):
if flag:
x: str
else:
x: int
x = 1 # error: [conflicting-declarations] "Conflicting declared types for `x`: `str` and `int`"
Incompatible declarations for 2 (out of 3) types
def _(flag1: bool, flag2: bool):
if flag1:
x: str
elif flag2:
x: int
# Here, the declared type for `x` is `int | str | Unknown`.
x = 1 # error: [conflicting-declarations] "Conflicting declared types for `x`: `str` and `int`"
Incompatible declarations with repeated types
def _(flag1: bool, flag2: bool, flag3: bool, flag4: bool):
if flag1:
x: str
elif flag2:
x: int
elif flag3:
x: int
elif flag4:
x: str
else:
x: bytes
x = "a" # error: [conflicting-declarations] "Conflicting declared types for `x`: `str`, `int` and `bytes`"
Incompatible declarations with bad assignment
def _(flag: bool):
if flag:
x: str
else:
x: int
# error: [conflicting-declarations]
# error: [invalid-assignment]
x = b"foo"
No errors
Currently, we avoid raising the conflicting-declarations for the following cases:
Partial declarations
def _(flag: bool):
if flag:
x: int
x = 1
Partial declarations in try-except
Refer to https://github.com/astral-sh/ruff/issues/13966
def _():
try:
x: int = 1
except:
x = 2
x = 3