python / python/mypy

warn-unreachable behaves differently on else-return than on bare return

Open
#10,773 6 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-error-reporting topic-reachability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy --warn-unreachable will error on an unreachable return after an if block but not a semantically equivalent else: return ... after an if block. This shows up in platform checking logic, as an example of "unreachable code" which mypy understands and allows.

Based on what I found in existing warn-unreachable issues, there's no report of this same issue.

To Reproduce

Run mypy --warn-unreachable on the two following samples.

This passes:

def foo():
    if sys.platform != "win32":
        return 1
    else:
        return 0

This fails (on Linux/macOS. Use == "win32" to observe on Windows):

def foo():
    if sys.platform != "win32":
        return 1
    return 0

I also put together a small example dir of this in a github repo, if that makes it easier:
https://github.com/sirosen/repro/tree/2a56d3b/mypy-issues

Expected Behavior

mypy should pass on both of these, as they are the same.

Your Environment

  • Mypy version used: 0.910

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the two examples with mypy --warn-unreachable and compare how the type checker handles the bare return and the else branch. Trace the unreachable-code analysis and add regression coverage for platform checks; done means both semantically equivalent samples receive the expected result.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.