ITADN

Missed type narrowing in `assert len(r) == …` which should imply `r` is not None

#11365Openjmarshall 创建于 2026-04-07
enhancement request
J
jmarshallcommented
In the following code, after the first `assert` it would seem that the type of `r` could be narrowed to `list[int]`, which would prevent the pyright diagnostic on the second `assert`: ```python def foo() -> list[int] | None: return [28, 37] def bar(): r = foo() reveal_type(r) # list[int] | None assert len(r) == 2 reveal_type(r) # list[int] | None but could be list[int] assert 28 in r # error: Operator "in" not supported for types … and "list[int] | None" ``` **Describe the solution you’d like** Use of `len(r)` within the assert implies that afterwards `r` cannot be None, so its type can be narrowed to `list[int]`. With that information, the types for the `in` operator are appropriate and so there is no type error. (This could be worked around with `assert r and len(r) == 2` but it would be good if the existing code were diagnostic-free too.)
0 条评论