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
#7
(Jan-16-2020, 09:42 AM)hobbitdur Wrote: And my class Building is Hashable.
No, it's not hashable*, because one of the fields is dict, which is mutable and not hashable, thus the whole Building dataclass is not hashable*.
as it says in the docs:

Quote:hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().

EDIT, based on the discussion below, to avoid confusion:
* hashable in the sense that when you pass object to hash() function it will not raise error, not that it is instance of collections.abc.Hashable and provide __hash__() method
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, 09:49 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,097 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