Skip to content

False positive: Statement is unreachable [unreachable] #12784

@mortoray

Description

@mortoray

Bug Report

This code causes mypy to emit an [unreachable] error.

def reader(value):
	last_msg_id = None
	for message_raw in [1,2]:
		msg_id = value
		if last_msg_id is None:
			last_msg_id = msg_id
		else:
			print("here")
				
reader(1)
$ env/bin/mypy /tmp/sample.py 
/tmp/sample.py:8: error: Statement is unreachable  [unreachable]

Running the program emits "here", so clearly it is reachable. Logical analysis also indicates it is reachable.

$ env/bin/mypy --version
mypy 0.950 (compiled: yes)
$ env/bin/python --version
Python 3.10.4

I'm not sure what is special about this structure that triggers the false positive. It's a reduced down version of a websocket server I have, where the code looks more like this:

import json

def decode_msg(text: str) -> dict:
	return json.loads(text)

async def reader(websocket):
	last_msg_id = None
	async for message_raw in websocket:
		msg = decode_msg(message_raw)
		msg_id = msg['msg_id']
		if last_msg_id is None:
			last_msg_id = msg_id
		else:
			if msg_id != last_msg_id+1:
				print("bad")

Which also generates the error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-reachabilityDetecting unreachable code

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions