python / python/mypy

Function that does type checks on generic classes' attribute not recognized

Open
#14,233 1 comment 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

Hi, I'm running into this behaviour that I think is a bug: it's like we can't annotate a function that does type checks on generic classes' attribute.

This might be a duplicate of #13619, but I'm not sure.

To Reproduce

from typing import Union, Generic, TypeVar, List, Type

_Types = Union[set, tuple]
_T = TypeVar('_T', bound=_Types)

class Thing:
    values: List['Value[_Types]']
    def filtervalues(self, *types:Type[_T]) -> List['Value[_T]']:
        return list(filter(lambda v:isinstance(v.val, types), self.values))

class Value(Generic[_T]):
    val: _T

if 1 in Thing().filtervalues(set, tuple)[0].val:
    print()

Expected Behavior

No errors.

Actual Behavior

Getting errors:

mypy-issue.py:14: error: Argument 1 to "filter" has incompatible type "Callable[[Value[Union[Set[Any], Tuple[Any, ...]]]], bool]"; expected "Callable[[Value[Union[Set[Any], Tuple[Any, ...]]]], TypeGuard[Value[_T]]]"  [arg-type]
mypy-issue.py:19: error: Value of type variable "_T" of "filtervalues" of "Thing" cannot be "Collection[Any]"  [type-var]

Your Environment

  • Mypy version used: mypy 0.991 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.10.8

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 Python reproducer in mypy-issue.py and run it with mypy using the environment described in the report, then compare the diagnostics with duplicate issue #13619. Done means the generic attribute type check is accepted without the reported arg-type and type-var errors.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.