python / python/mypy

`--warn-unreachable` doesn't flag unnecessary comparison to `None`

Open
#20,060 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Here is a full example:


from random import randrange



def f(x: int) -> int | None:

    return None if x == 0 else 2 * x



def g(x: int) -> int:

    return 2 * x



if __name__ == '__main__':

    if f(randrange(10)) is None:

        print('f: got 0')



    if g(randrange(10)) is None:  # <-- unreachable but not flagged

        print('g: got 0')

mypy --strict --warn-unreachable does not raise any warnings, but it should. So this is a FALSE NEGATIVE bug. Or a new feature, whatever, but in any case this situation should be flagged.

Originally posted by @nickdrozd in #18386

This might be intentional, but I think it's counterintuitive and I can't really see a benefit. Making an issue to make sure I get around to investigating this.

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 reproducing the provided example with mypy --strict --warn-unreachable and confirm that the comparison involving g is not reported. Trace the --warn-unreachable analysis for comparisons against None; done means the unnecessary comparison is diagnosed without incorrectly flagging the reachable comparison involving f.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.