How to make Mypy recognize frozen dataclasses as Hashable

Viewed 119

So creating effectively hashable dataclasses with frozen=True is great, but it breaks some of my ability to typecheck code I write since mypy doesn't seem to automagically recognize frozen dataclasses as instances of Hashable. This makes sense of course, since I haven't explicitly extended that class (it would be amazing if it could infer), but has anyone out there found an elegant solution/workaround for this issue?

1 Answers

Looking deeper my issue was actually a variance issue due to working with lists of such dataclasses. The support is there, just be mindful of variance :)

In my cases using Sequence[Hashable] instead of List[Hashable] in my type annotations appeased mypy. Turns out that since list elements are mutable they are invariant whereas sequences are covariant. See https://mypy.readthedocs.io/en/stable/common_issues.html#invariance-vs-covariance

Related