pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

Type narrowing via `assert type(x) is X `

Open mexus opened this issue 8 months ago • 0 comments

Describe the Bug

Currently the following code triggers a type error (pyrefly 0.16.1):

def verify_type(input: int):
    pass


def foo(x: int | None) -> None:
    assert type(x) is int
    verify_type(x)

Leads to

Argument `int | None` is not assignable to parameter `input` with type `int` in function `reveal_type`

Link to the pyright playground with the sample: https://pyright-play.net/?code=CYUwZgBGD20BQA8BcECWA7ALhAPhActOiAJQQC0AfAUSEgFARMQCGAzmyAE7aYCeABxCIyqNmiyNmXEADcQLADYB9fkJFMAxBAC2gvhEwALDAGtxxsWnEZMQA

Mypy also respects the assertion.

While assert isinstance(..) works just fine with pyrefly, these approaches are technically not the same, and some code uses specifically the pattern assert type(x) is y for type checking.

It would be great if pyrefly also supports this kind of type narrowing, although I'm not quite sure how popular the pattern is, hence usefulness should be decided my someone more experienced with python than me.

Thanks!

Sandbox Link

https://pyrefly.org/sandbox/?code=MQAg6gpgNgxg9gWwiALnVALZAFAngJwgDMpcQBlAQwDsATAIzgA8AaTASwGcQuRKQADpQDmEAFCgA7lkIhccAK4gYNEJPzsUENpwyVZNWiCgR91PowUpUuAe2rCe5vCgxxqAOgkSQACQgGBsqKAiYgRKYoCoTccEQc3JyGjEwAXD4AtCAA4hDWhJRQGSjsSDYCyDBYMADW9o4REAyUtZkgAKqcyIQAbqZQAPoothAAFACUqOj2nBUw1vYR+IRGwxWcbRBMFRpI1NaSmhiYyACSACIAouGR0RDcrpQHyJwKAgJw+NajEB7CHnwrHB4AhQnltCBhHBitDaMR7Jp2O42G4+vg2HkYOM2mANFo+HQQPgFM5cK53ME4SBaOxCPNSE45Ip8CB6Pg4JIuvgxGIiOyEOV6jxQZ9rAAqHlw+JEOBwUZpJzWAA+IAAcu4IJMMgA+NUa9IgQ18Thc6xrMZMSa8ewoMRGokQPqFIYjeXYoA

(Only applicable for extension issues) IDE Information

No response

mexus avatar May 22 '25 19:05 mexus