Skip to content

--warn-unreachable false positive with minimal example without types explicitly set #7204

Description

@LefterisJP

Hello,

I just downloaded the new mypy v0.720 and am playing with the --warn-unreachable-flag in my projects.

I noticed one occasion where there is something that seems like a false positive, so I am making an issue for it with a minimal reproducible example.

Version

mypy==0.720
mypy-extensions==0.4.1

source code example

importsysfromtypingimportOptionalfound_id=Nonesymbols_list= [{'symbol': 'A', 'id': 1}, {'symbol': 'B', 'id': 2}, {'symbol': 'B', 'id': 3}]
forentryinsymbols_list:
ifentry['symbol'] =='B':
iffound_id:
print('error, symbol found multiple times!')
sys.exit(1)
found_id=entry['id']

This when tested with mypy test.py --warn-unreachable returns:

test.py:10: error: Statement is unreachable

So essentially telling us that if found_id is never entered due to the found_id type being None. But in reality the type should be Optional[int] since you can see that it's set to entry['id'] later.

If you explicitly set the types mypy no longer complains:

importsysfromtypingimportOptionalfound_id: Optional[int] =Nonesymbols_list= [{'symbol': 'A', 'id': 1}, {'symbol': 'B', 'id': 2}, {'symbol': 'B', 'id': 3}]
forentryinsymbols_list:
ifentry['symbol'] =='B':
iffound_id:
print('error, symbol found multiple times!')
sys.exit(1)
assertisinstance(entry['id'], int)
found_id=entry['id']

Bug or not

Essentially I am not sure if this is intended behaviour or not. After writing this issue down I realize it all boils down to the matter of mypy not correctly inferring type of found_id.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions