3
@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?

rickythefox
  • 6,601
  • 6
  • 40
  • 62
  • 1
    Is this warning coming from PyCharm or some other IDE? Seems like it's not handling dataclasses properly. Maybe try disabling that inspection in the settings or adding `#noqa` to the line – rdas Oct 09 '22 at 10:16
  • @rdas, yes, apparently a known bug in PyCharm. Closing this, thanks. – rickythefox Oct 09 '22 at 12:22

2 Answers2

4

Apparently a known bug in PyCharm, tracked here

rickythefox
  • 6,601
  • 6
  • 40
  • 62
1

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:

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.

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41