Skip to content

False positive "Statement is unreachable" when checking if typevar is None #18126

Closed
@Cnoor0171

Description

@Cnoor0171

Bug Report

Mypy doesn't seem to like it when you check if an argument with typevar type is checked to see if it is None. It incorrectly reports error: Statement is unreachable [unreachable]

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&flags=strict%2Cwarn-unreachable&gist=ceb8193f19f8b53a55dea70fad802469

import typing as t

T = t.TypeVar("T")

def foo(arg: T) -> None:
    if arg is None:
        return None
    # Do something with arg
    return None


foo(None) ## Allowed
foo(123)

Run mypy with --warn-unreachable flag

Expected Behavior

No errors

Actual Behavior

$ mypy .vscode/scratch.py
.vscode/scratch.py: note: In function "foo":
.vscode/scratch.py:9: error: Statement is unreachable  [unreachable]
Found 1 error in 1 file (checked 1 source file)

The error seems to only happen when checking if arg is None, but not with other types. For example, I tired changing if arg is None: line to the following and these were the results.

  1. if arg is True: -> no errors
  2. if isinstance(arg, int): -> no errors
  3. if isinstance(arg, type(None)): -> unreachable error
  4. if arg == None: -> No error

Also, changing the type to T | None removes the error as well.

Your Environment

  • Mypy version used: mypy 1.13.0 (compiled: yes)
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files): warn_unreachable = True
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions