python / python/mypy

TypeGuard does not narrow when statement compares for identity (`is True`)

Open
#17,483 6 comments 0 reactions 1 assignee View on GitHub

@flaeppe is already working on this.

Since Jul 6, 2024.

bug topic-type-narrowing topic-typeguard-typeis
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

In the example below f is a TypeGuard that mypy fails to narrow the type with when the statement compares with identity (is True)

To Reproduce

https://mypy-play.net/?mypy=master&python=3.12&flags=strict&gist=688d7597c968ed90ecdd8d4bf2b3a8a3

from typing import TypeGuard

def f(value: str) -> TypeGuard[int]:
    return True

# This should narrow to "builtins.int"
by_identity = "123"
assert f(by_identity) is True
reveal_type(by_identity)  # Revealed type is "builtins.str"

Expected Behavior

Revealed type is "builtins.int"

Actual Behavior

Revealed type is "builtins.str"

Your Environment

  • Mypy version used: 1.10.1 (and master)
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.