Skip to content

Commit

Permalink
opt_frozen_dataclass: Enable hashing with -O
Browse files Browse the repository at this point in the history
  • Loading branch information
inducer committed Dec 3, 2024
1 parent 52688c9 commit 9c936f8
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions pytools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2987,7 +2987,7 @@ def opt_frozen_dataclass(
repr: bool = True,
eq: bool = True,
order: bool = False,
unsafe_hash: bool = False,
unsafe_hash: bool | None = None,
match_args: bool = True,
kw_only: bool = False,
slots: bool = False,
Expand All @@ -3000,16 +3000,29 @@ def opt_frozen_dataclass(
this decorator avoid when the interpreter runs with "optimization"
enabled.
The resulting dataclass supports hashing unless *eq* is set to *False*,
if *unsafe_hash* is left at the default or set to *True*.
.. versionadded:: 2024.1.18
"""
def map_cls(cls: type[T]) -> type[T]:
# This ensures that the resulting dataclass is hashable with and without
# __debug__, unless the user overrides unsafe_hash.
if (eq
and not __debug__
and unsafe_hash is None
and "__hash__" not in cls.__dict__):
loc_unsafe_hash = True
else:
loc_unsafe_hash = False

from dataclasses import dataclass
return dataclass(
init=init,
repr=repr,
eq=eq,
order=order,
unsafe_hash=unsafe_hash,
unsafe_hash=loc_unsafe_hash,
frozen=__debug__,
match_args=match_args,
kw_only=kw_only,
Expand Down

0 comments on commit 9c936f8

Please sign in to comment.