From 4e4a925f0b63de1a45905447be043ef30b86adcb Mon Sep 17 00:00:00 2001 From: Dominic Kempf <dominic.kempf@iwr.uni-heidelberg.de> Date: Thu, 28 Feb 2019 04:41:28 +0100 Subject: [PATCH] Cache hash value of ImmutableRecord Due to the data structure to being intended immutable, the hash value cannot change during object lifetime. This commit caches the value upon first evaluation. --- pytools/__init__.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/pytools/__init__.py b/pytools/__init__.py index 57e3378..c096e99 100644 --- a/pytools/__init__.py +++ b/pytools/__init__.py @@ -315,12 +315,18 @@ class Record(RecordWithoutPickling): class ImmutableRecordWithoutPickling(RecordWithoutPickling): "Hashable record. Does not explicitly enforce immutability." + def __init__(self, *args, **kwargs): + RecordWithoutPickling.__init__(self, *args, **kwargs) + self._cached_hash = None def __hash__(self): - return hash( + if self._cached_hash is None: + self._cached_hash = hash( (type(self),) + tuple(getattr(self, field) for field in self.__class__.fields)) + return self._cached_hash + class ImmutableRecord(ImmutableRecordWithoutPickling, Record): pass -- GitLab