Skip to content

isinstance checks cause type declarations to leak from the binder #1568

Closed
@ddfisher

Description

@ddfisher

The problem with this is most easily visible with list comprehensions:

lst = [1, 2, 3]  # type: List[Union[int, str]]
[x if isinstance(x, int) else 0 for x in lst]
reveal_type([x for x in [4, 5, 6]])
$ python3 -m mypy ~/test.py
test.py:3: error: Revealed type is 'builtins.list[Union[builtins.int, builtins.str]]'

This happens because of this line in the binder, which always adds the declared type of a variable to the topmost frame whenever a binding for it is pushed: https://github.com/python/mypy/blob/master/mypy/checker.py#L127

This is obviously a bug, but it's not yet clear what the best way to fix the issue is. The binder is small, but complicated -- perhaps the best fix is it rewrite it in a more understandable/robust way?

This issue is the reason mypy still has a self-typecheck error with #1562.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions