Python Forum
Creating a set with dataclass and dict
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a set with dataclass and dict
#10
as stated in the docs collections.abc.Hashable are classes that provide __hash__() method. i.e. it doesn't mean it's guaranteed that when you call that method it will not raise error.
Not exactly the same, but it similar - if you look at data model docs for object.__hash__()
Quote:A class which defines its own __hash__() that explicitly raises a TypeError would be incorrectly identified as hashable by an isinstance(obj, collections.abc.Hashable) call.
Your Buildings has __hash__ method but when called it raises TypeError.

dataclasses.dataclass [may] provides __hash__() - check unsafe_hash attribute for details. In your case it will be forced to create __hash__ method because both frozen and eq are set True. However when you it is called when creating the set you get the TypeError. You will get same error if you try to call hash(some_dict).

Note that this is not unique to your case., e.g.

import collections.abc
foo = ([1, 2], 'a')
print(type(foo))
print(isinstance(foo, collections.abc.Hashable))
hash(foo)
Output:
<class 'tuple'> True Traceback (most recent call last): File "/home/buran/sandbox/pyforum.py", line 5, in <module> hash(foo) TypeError: unhashable type: 'list'
Bottom line - be careful with nested data structures.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Creating a set with dataclass and dict - by buran - Jan-16-2020, 11:05 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  append str to list in dataclass flash77 6 712 Mar-14-2024, 06:26 PM
Last Post: flash77
  Sort a dict in dict cherry_cherry 4 91,156 Apr-08-2020, 12:25 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020