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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.