Wraps an object, mapping __eq__ on wrapper to "is" on wrapped. Since __eq__ is based on object identity, it's safe to also define __hash__ based on object ids. This lets us add unhashable types like trackable _ListWrapper objects to object-identity collections.
| 23 | |
| 24 | |
| 25 | class _ObjectIdentityWrapper(object): |
| 26 | """Wraps an object, mapping __eq__ on wrapper to "is" on wrapped. |
| 27 | |
| 28 | Since __eq__ is based on object identity, it's safe to also define __hash__ |
| 29 | based on object ids. This lets us add unhashable types like trackable |
| 30 | _ListWrapper objects to object-identity collections. |
| 31 | """ |
| 32 | |
| 33 | def __init__(self, wrapped): |
| 34 | self._wrapped = wrapped |
| 35 | |
| 36 | @property |
| 37 | def unwrapped(self): |
| 38 | return self._wrapped |
| 39 | |
| 40 | def __eq__(self, other): |
| 41 | if not isinstance(other, _ObjectIdentityWrapper): |
| 42 | raise TypeError("Cannot compare wrapped object with unwrapped object") |
| 43 | |
| 44 | return self._wrapped is other._wrapped # pylint: disable=protected-access |
| 45 | |
| 46 | def __ne__(self, other): |
| 47 | return not self.__eq__(other) |
| 48 | |
| 49 | def __hash__(self): |
| 50 | # Wrapper id() is also fine for weakrefs. In fact, we rely on |
| 51 | # id(weakref.ref(a)) == id(weakref.ref(a)) and weakref.ref(a) is |
| 52 | # weakref.ref(a) in _WeakObjectIdentityWrapper. |
| 53 | return id(self._wrapped) |
| 54 | |
| 55 | def __repr__(self): |
| 56 | return "<{} wrapping {!r}>".format(type(self).__name__, self._wrapped) |
| 57 | |
| 58 | |
| 59 | class _WeakObjectIdentityWrapper(_ObjectIdentityWrapper): |