[Python-Dev] Dataclasses and correct hashability
Nick Coghlan
ncoghlan at gmail.com
Mon Feb 5 17:56:40 EST 2018
More information about the Python-Dev mailing list
Mon Feb 5 17:56:40 EST 2018
- Previous message (by thread): [Python-Dev] Dataclasses and correct hashability
- Next message (by thread): [Python-Dev] Dataclasses and correct hashability
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 6 February 2018 at 03:47, Guido van Rossum <guido at python.org> wrote: > If there's going to be an API for it, it should be in the class, not > something that mutates the class afterwards. Something I realised after posting the __class__ setting idea is that you can actually use a comparable trick to inject an unsafe hash from the frozen version into the mutable version: >>> from dataclasses import dataclass >>> @dataclass ... class Example: ... a: int ... b: int ... >>> c = Example(1, 2) >>> hash(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'Example' >>> @dataclass(frozen=True) ... class LockedExample(Example): ... pass ... >>> Example.__hash__ = LockedExample.__hash__ >>> hash(c) 3713081631934410656 So "unsafe_hash=True" would just be a shorthand spelling of that which skips creating the full frozen version of the class (and with the explicit parameter, we can better document the risks of making something hashable without also freezing it post-creation). Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
- Previous message (by thread): [Python-Dev] Dataclasses and correct hashability
- Next message (by thread): [Python-Dev] Dataclasses and correct hashability
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-Dev mailing list