From be3a87f6dd8e3475b64c44289acc8c3c43bcb34d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Ma=C5=9Blanka?= <piotr.maslanka@henrietta.com.pl> Date: Sat, 25 Apr 2020 16:35:57 +0200 Subject: [PATCH] improve HashableWrapper --- satella/coding/structures/hashable_objects.py | 15 ++++++++++----- satella/coding/structures/proxy.py | 2 +- tests/test_coding/test_structures.py | 3 +++ 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/satella/coding/structures/hashable_objects.py b/satella/coding/structures/hashable_objects.py index ede85641..33a8fb51 100644 --- a/satella/coding/structures/hashable_objects.py +++ b/satella/coding/structures/hashable_objects.py @@ -1,6 +1,11 @@ -def HashableWrapper(obj): +from .proxy import Proxy + + +class HashableWrapper(Proxy): """ - A decorator that makes given objects hashable by their id. + A class that makes given objects hashable by their id. + + Note that this class will return a proxy to the object, and not the object itself. Use like: @@ -12,6 +17,6 @@ def HashableWrapper(obj): >>> a.a = 4 >>> assert a.a == 4 """ - if not hasattr(obj, '__hash__'): - obj.__hash__ = lambda self: hash(id(self)) - return obj + + def __hash__(self): + return hash(id(self)) diff --git a/satella/coding/structures/proxy.py b/satella/coding/structures/proxy.py index 1e11ce04..3d5109d2 100644 --- a/satella/coding/structures/proxy.py +++ b/satella/coding/structures/proxy.py @@ -42,7 +42,7 @@ class Proxy(tp.Generic[T]): return getattr(self.__obj, item) def __delattr__(self, item): - del self.__obj[item] + delattr(self.__obj, item) def __int__(self): return int(self.__obj) diff --git a/tests/test_coding/test_structures.py b/tests/test_coding/test_structures.py index 56a2c1b8..cb83fb6b 100644 --- a/tests/test_coding/test_structures.py +++ b/tests/test_coding/test_structures.py @@ -99,6 +99,9 @@ class TestMisc(unittest.TestCase): def __call__(self, *args, **kwargs): return 5 + def __hash__(self): + raise TypeError() + nh = NotHashable(5) nw = HashableWrapper(nh) self.assertEqual(nw.a, 5) -- GitLab