basedmypy icon indicating copy to clipboard operation
basedmypy copied to clipboard

widen type at start of loop with assignment

Open KotlinIsland opened this issue 2 years ago • 3 comments

a: int | None
a = None
for _ in range(2):
    reveal_type(a)  # None
    a = 1

a should be widened to int | None at the start of the loop.

workaround

a: int | None
a = cast(int | None, None)
for _ in range(2):
    reveal_type(a)  # int | None
    a = 1

KotlinIsland avatar Nov 02 '23 00:11 KotlinIsland

  • upstream https://github.com/python/mypy/issues/11612

KotlinIsland avatar Jan 13 '24 08:01 KotlinIsland

this is more of an issue in basedmypy than upstream, since variables are narrowed on initial assignment so it's easier to run into

a: int | None = None
for _ in range(2):
    reveal_type(a)  # None
    a = 1

DetachHead avatar Jan 13 '24 08:01 DetachHead

p-1 I suppose?

KotlinIsland avatar Jan 13 '24 08:01 KotlinIsland