Descriptors don't work with `TypeGuard`
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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