Skip to content

Type narrowing via assert type(x) is X and assert type(x) == X #335

@mexus

Description

@mexus

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

Metadata

Metadata

Assignees

Labels

help wantedLarger than "good first issue", but still well-defined and ready for someone to pick uppytorch

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions