Skip to content

Constrained TypeVar resolves to subtype instead of constraint #2370

@migeed-z

Description

@migeed-z

Describe the Bug

When a constrained TypeVar is called with a subtype of a constraint (e.g. AnyStr = TypeVar("AnyStr", str, bytes)) pyrefly resolves to the subtype instead of the constraint. For example, passing MyStr(str) should resolve AnyStr to str, not MyStr.

`from typing import TypeVar, assert_type

AnyStr = TypeVar("AnyStr", str, bytes)

def concat(x: AnyStr, y: AnyStr) -> AnyStr:
return x + y

class MyStr(str): ...

def test(m: MyStr, s: str):
assert_type(concat(m, m), str) # pyrefly says MyStr, should be str
assert_type(concat(m, s), str) # pyrefly says MyStr and also rejects s`

Note: this unittest is already available in the codebase.

Sandbox link:

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0AVZjABqqSgBo6qOHBh8A%2Bk2IwAOunUBBdKQDKDSnQC8g4WMoAKVSG16D1qXANTspBvACU69Zhhg6AMa46AGoDBb4iHS2%2BpJ0pFExBh50ALQAfNE6sYjqdPl0lDAMAK6U6HT4dADU8d4hUDJwdACydpZOlB5RhL31vv7uThY0UW2xjlGd3XkFTfIMSsIWQSFhI1I0Ho7JBQDEdGRFYFCkdGikzePO5wAWuCVQmHTYMOf2FXOyC0sqK8GhcI0Rzbd5dfaHUjHU7nVCXVrtaRYaRQOC4QowABWMACDGacHUIAkIBKDGgcBI5EQIAOAFUyVAIEw6GASiEycECRosH4WbwaGEFOgSjRXpZIpx0AwUhkwblPvkiqVyizrAA5EViqLAfAAX2shOJRz8p0IDFoUAoBwAClCTWc0Fg8FVVpA2GUwhBgoR1AddDA3rcGAxiHBEAB6cPGk6kQi8NjhmDocOYXABODh10Qd2UT3BcN8wyoABuqGgqGwsECwTdHo5FVwxHrFPUZAY93QqWL8jgXoqJmsAGZCABGABMBvQIF1xNQuIg3YAYtAYBRHTgCJTp0A

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions