Skip to content

Type narrowing for typeVars is wrong #1274

@oriori1703

Description

@oriori1703

Describe the Bug

Actual:

from typing import reveal_type


def test[T: int | str](value: T) -> T:
    if isinstance(value, int):
        reveal_type(value) # revealed type: int
        return value # This errors
    else:
        reveal_type(value)
        return value # This is ok

Python: 3.13

Type narrowing for typeVars seems to be wrong.
After narrowing a variable that has a typeVar as its type, Pyrefly seems to forget that it is a typeVar so, it is not compatible with the original type anymore, even though the value didn't change.

In the example above I would expect Pyrefly to narrow the type of value to T & int or to also narrow T to int.

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN2UYANxiooAfSbEYAHXRy5mGGEbwGAbQAqiTun4AfOnAaUAugAohYgK4wdmgJR0AtAD462uXW%2BcVEOKzGGADGMJY2MAA0ugwOiF4%2BiYIiYpLMYVZQtg4Jid6CDNaU6HSZtrl0MFBwdhVJwqISUhkROSV5%2BTCFxaURciCRIGSCYFCkhAy0UBQAxHQACqQjY0YYOAR0wbjokGxFqAwQ24RycwDKMDB0ABYMDMRwiAD0T8PKY4S8bE8w6E%2BYuGCcCeWx2ED2lAORz%2BdDAvDoqCs0FQ2Fgm22u32h22dFwxGx6DgJ3QZAY122zhElACOIAvHQZCAAMyEACMTMZ-QAvoNUMFDiIAGLQGAUNBYPBEMggLlAA

Metadata

Metadata

Assignees

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions