Skip to content
Snippets Groups Projects
Commit be3a87f6 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

improve HashableWrapper

parent bb34c2a7
No related branches found
No related tags found
No related merge requests found
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))
......@@ -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)
......
......@@ -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)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment