Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected type 'Iterable' (matched generic type 'Iterable[SupportsLessThanT]')

@dataclass(frozen=True, eq=True, order=True)
class C:
    x: int

l = [C(1), C(2), C(1)]
print(sorted(l))

The above code works but gives a warning: Expected type 'Iterable' (matched generic type 'Iterable[SupportsLessThanT]'), got 'list[C]' instead.

I think the order=True param passed to @dataclass should result in generation of __lt__ etc and thus confirm to SupportsLessThanT?

An explicit implementation of __lt__ silences the warning, but how do I silence it without?

like image 612
rickythefox Avatar asked Sep 02 '25 06:09

rickythefox


2 Answers

Apparently a known bug in PyCharm, tracked here

like image 190
rickythefox Avatar answered Sep 04 '25 18:09

rickythefox


Just to add a bit of additional context here, as it seems it isn't mentioned in the bug tracker explicitly...

This is a bug that likely stems from the fact that the dataclass magic is adding methods and annotations dynamically. Something that is not in the nature of static type checkers to pick up. They solve situations like this with special plugins that are tailored to certain specifications.

A related issue comes up when people try to mimic dataclass-like behavior in their own code, i.e. constructing signatures and/or adding annotations at runtime. They always run into the same obstacle of static type checkers being completely oblivious to their intent.

Static type checkers don't execute your code, they just read it.

Related:

  • How to typehint dynamic class instantiation like pydantic and dataclass?
  • How can i type hint the init params are the same as fields in a dataclass?

I have no affiliation with the JetBrains folks. Just wanted to point this out to be fair because I would consider this a more "forgivable" bug as they are forced to "hack around" PEP 557.

like image 43
Daniil Fajnberg Avatar answered Sep 04 '25 19:09

Daniil Fajnberg