Skip to content

Commit

Permalink
feat: hash method
Browse files Browse the repository at this point in the history
Mimicing the behavior of JAX

Signed-off-by: nstarman <[email protected]>
  • Loading branch information
nstarman committed Mar 3, 2024
1 parent ff717da commit afb99ad
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/jax_quantity/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import operator
from collections.abc import Callable, Sequence
from dataclasses import replace
from dataclasses import fields, replace
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, final

import equinox as eqx
Expand Down Expand Up @@ -264,6 +264,25 @@ def reshape(self, *args: Any, order: str = "C") -> "Quantity":
__tracebackhide__ = True # pylint: disable=unused-variable
return replace(self, value=self.value.reshape(*args, order=order))

# ===============================================================
# Python stuff

def __hash__(self) -> int:
"""Hash the object as the tuple of its field values.
This raises a `TypeError` if the object is unhashable,
which JAX arrays are.
Examples
--------
>>> from jax_quantity import Quantity
>>> q1 = Quantity(1, "m")
>>> try: hash(q1); except TypeError as e: print(e)
unhashable type: 'Quantity'
"""
return hash(tuple(getattr(self, f.name) for f in fields(self)))

# ===============================================================
# I/O

Expand Down

0 comments on commit afb99ad

Please sign in to comment.