basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

narrowing should work on values that are arent literals if their type is `@final`

Open KotlinIsland opened this issue 1 year ago • 3 comments

def f(a: int | None, b: int):
    if a == b:
        reveal_type(a)  # int | None
    if b == a:
        reveal_type(a)  # int | None

KotlinIsland avatar Jun 03 '24 23:06 KotlinIsland

the issue is actually that it only narrows literals:

def f(a: int | None, b: int):
    if a == 1:
        reveal_type(a)  # Literal[1]
    if a == b:
        reveal_type(a)  # int | None

upstream issue: https://github.com/microsoft/pyright/issues/8065

DetachHead avatar Jun 04 '24 00:06 DetachHead

actually this would be unsafe because a subtype of int could define a custom __eq__. so this should only work if the class is @final

DetachHead avatar Jun 25 '24 19:06 DetachHead

narrowing with is instead of == should also work because it doesn't use __eq__

DetachHead avatar Jun 29 '24 04:06 DetachHead