Include Type in a Dataclass Hash Function

I have a hierarchy of frozen dataclasses, and I need to implement hashing for these dataclasses such that the hashes of every unique instance across the whole hierarchy are unique. I am defining “unique” here to mean that either the fields or the type of two instances differ. However, since the default dataclass __hash__ is a function only of the dataclass fields and not of the type, instances of different dataclass types which share the same fields hash to the same value by default.

Simplified Example

Below is a 3-level nested dataclass.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from dataclasses import dataclass
import abc
@dataclass(frozen=True)
class Element(abc.ABC):
pass
@dataclass(frozen=True)
class StepType(Element, abc.ABC):
@classmethod
def name(cls):
return cls.__name__
class Skip(StepType): pass
class Hop(StepType): pass
@dataclass(frozen=True)
class Stepper(Element, abc.ABC):
step_type: StepType = Skip()
foo: int = 1
@abc.abstractmethod
def step(self):
pass
@dataclass(frozen=True)
class Single(Stepper):
def step(self):
return self.step_type.name() + " once"
@dataclass(frozen=True)
class Double(Stepper):
def step(self):
return self.step_type.name() + " twice"
@dataclass(frozen=True)
class Speed(Element, abc.ABC):
@abc.abstractmethod
def how_fast(self):
pass
@dataclass(frozen=True)
class Slow(Speed):
def how_fast(self):
return "real slow"
@dataclass(frozen=True)
class Fast(Speed):
def how_fast(self):
return "quickly"
@dataclass(frozen=True)
class Walker:
speed: Speed = Slow()
stepper: Stepper = Single()
def walk(self):
return " ".join([self.stepper.step(), self.speed.how_fast()])
</code>
<code>from dataclasses import dataclass import abc @dataclass(frozen=True) class Element(abc.ABC): pass @dataclass(frozen=True) class StepType(Element, abc.ABC): @classmethod def name(cls): return cls.__name__ class Skip(StepType): pass class Hop(StepType): pass @dataclass(frozen=True) class Stepper(Element, abc.ABC): step_type: StepType = Skip() foo: int = 1 @abc.abstractmethod def step(self): pass @dataclass(frozen=True) class Single(Stepper): def step(self): return self.step_type.name() + " once" @dataclass(frozen=True) class Double(Stepper): def step(self): return self.step_type.name() + " twice" @dataclass(frozen=True) class Speed(Element, abc.ABC): @abc.abstractmethod def how_fast(self): pass @dataclass(frozen=True) class Slow(Speed): def how_fast(self): return "real slow" @dataclass(frozen=True) class Fast(Speed): def how_fast(self): return "quickly" @dataclass(frozen=True) class Walker: speed: Speed = Slow() stepper: Stepper = Single() def walk(self): return " ".join([self.stepper.step(), self.speed.how_fast()]) </code>
from dataclasses import dataclass
import abc

@dataclass(frozen=True)
class Element(abc.ABC):
    pass

@dataclass(frozen=True)
class StepType(Element, abc.ABC):
    @classmethod
    def name(cls):
        return cls.__name__

class Skip(StepType): pass
class Hop(StepType): pass

@dataclass(frozen=True)
class Stepper(Element, abc.ABC):
    step_type: StepType = Skip()
    foo: int = 1
    @abc.abstractmethod
    def step(self):
        pass

@dataclass(frozen=True)
class Single(Stepper):
    def step(self):
        return self.step_type.name() + " once"

@dataclass(frozen=True)
class Double(Stepper):
    def step(self):
        return self.step_type.name() + " twice"

@dataclass(frozen=True)
class Speed(Element, abc.ABC):
    @abc.abstractmethod
    def how_fast(self):
        pass

@dataclass(frozen=True)
class Slow(Speed):
    def how_fast(self):
        return "real slow"

@dataclass(frozen=True)
class Fast(Speed):
    def how_fast(self):
        return "quickly"

@dataclass(frozen=True)
class Walker:
    speed: Speed = Slow()
    stepper: Stepper = Single()

    def walk(self):
        return " ".join([self.stepper.step(), self.speed.how_fast()])

Inheritance Structure

Here’s summary of the inheritance structure of Element.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Element
|- StepType
| |- Skip
| |- Hop
|
|- Stepper
| |- Single
| |- Double
|
|- Speed
|- Slow
|- Fast
</code>
<code>Element |- StepType | |- Skip | |- Hop | |- Stepper | |- Single | |- Double | |- Speed |- Slow |- Fast </code>
Element
|- StepType
|  |- Skip
|  |- Hop
|
|- Stepper
|  |- Single
|  |- Double
|
|- Speed
   |- Slow
   |- Fast

Nesting Structure

Here’s summary of the nested fields structure of Walker.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Walker
|- stepper: Stepper
| |- step_type: StepType
|
|- speed: Speed
</code>
<code>Walker |- stepper: Stepper | |- step_type: StepType | |- speed: Speed </code>
Walker
|- stepper: Stepper
|  |- step_type: StepType
| 
|- speed: Speed

Tested Behavior

Different instances of Walker and its Element instances hash to the same value.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>a = Walker(speed=Slow(), stepper=Single())
b = Walker(speed=Fast(), stepper=Double(step_type=Hop()))
print(f"a: {hash(a)}nb: {hash(b)}")
</code>
<code>a = Walker(speed=Slow(), stepper=Single()) b = Walker(speed=Fast(), stepper=Double(step_type=Hop())) print(f"a: {hash(a)}nb: {hash(b)}") </code>
a = Walker(speed=Slow(), stepper=Single())
b = Walker(speed=Fast(), stepper=Double(step_type=Hop()))
print(f"a: {hash(a)}nb: {hash(b)}")
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>> a: -5704360693866892300
b: -5704360693866892300
</code>
<code>>> a: -5704360693866892300 b: -5704360693866892300 </code>
>> a: -5704360693866892300
   b: -5704360693866892300

Desired Behavior

I would like the hashes of unique Walker instances to be reliably different and maintain functionality for various dataclass features.

Constraints

  • This need not be done via overriding __hash__, it could be via creating new methods in Walker and/or Element. But it must be recursive since Element instances can contain other Elements to arbitrary depths. Ideally, I’d like to leverage the reliable default dataclass __hash__ rather than overriding it completely.
  • The hashes will be saved to and read from disk, so they must be consistent across runs. E.g., they can’t depend on id(self) like object.__hash__ does.
  • Everything except Walker must inherit from Element. I cannot refactor any of the dataclasses into regular classes, Enums, etc. I must use the dataclass framework.

Ideas

I think it would work well to add repr(type(self)) to the hash function as well as the fields.

Idea 1

My first idea was something like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Element:
def hash(self):
return hash(self) ^ hash(repr(type(self)))
</code>
<code>class Element: def hash(self): return hash(self) ^ hash(repr(type(self))) </code>
class Element:
    def hash(self):
        return hash(self) ^ hash(repr(type(self)))

But this doesn’t recurse down to nested Elements.

Idea 2

This is the best idea I have at the time of posting.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Element:
def __hash__(self):
return hash(
hash(repr(type(self))) ^
(hash(
hash((key, val)) for key, val in self.__dict__.items()
)**3
)
)
</code>
<code>class Element: def __hash__(self): return hash( hash(repr(type(self))) ^ (hash( hash((key, val)) for key, val in self.__dict__.items() )**3 ) ) </code>
class Element:
    def __hash__(self):
        return hash(
            hash(repr(type(self))) ^ 
            (hash(
                hash((key, val)) for key, val in self.__dict__.items()
                )**3
            )
        )

This does recurse, and it passes my unit tests, but it overrides the built-in dataclass __hash__. I’m worried this could create some broken corner cases. Any input on a more robust method, pointing out where this would break, or a simple thumbs up is appreciated.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật