python / python/mypy

Descriptors don't work with `TypeGuard`

Open
#16,828 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

The tool doesn't correctly interpret TypeGuard in the context of a descriptor.

To Reproduce

mypy-play.net gist

from __future__ import annotations

from typing import *
from typing_extensions import (
        TypeGuard,
        )

class SomeDescriptor:
    # simplified: no @overload for obj=None, klass=<type ...>
    def __get__(
            self, obj: object, klass: Optional[Type[object]] = None
            ) -> TypeGuard[DerivedClass]:
        return isinstance(obj, DerivedClass)

class BaseClass:
    described = SomeDescriptor()

class DerivedClass(BaseClass): pass


def problem(instance: BaseClass) -> None:

    if instance.described:
        reveal_type(instance)  # BaseClass      (expected: DerivedClass)
    else:
        reveal_type(instance)  # BaseClass      (correct)


def contrast(descr: SomeDescriptor, instance: BaseClass) -> None:

    if descr.__get__(instance):
        reveal_type(instance)  # DerivedClass   (correct)
    else:
        reveal_type(instance)  # BaseClass      (correct)

Expected Behavior

In problem(), the type of instance should be narrowed when instance.described is truthy.

Actual Behavior

While mypy understands that a TypeGuard returns a bool, it doesn't narrow the type when the TypeGuard returns True.

Your Environment

  • Mypy version used: 1.8.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.8, 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.

Research direction

Start with the linked mypy-play reproduction and compare the TypeGuard behavior in problem() with the working direct get call in contrast(). Trace the descriptor-based narrowing path and verify that instance is narrowed to DerivedClass in the truthy branch while the false branch remains BaseClass.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.