Skip to content

Instantly share code, notes, and snippets.

@dmrz
Last active January 31, 2018 20:10
Show Gist options
  • Save dmrz/96510fdfec0264baf6efc3d26c3e6463 to your computer and use it in GitHub Desktop.
Save dmrz/96510fdfec0264baf6efc3d26c3e6463 to your computer and use it in GitHub Desktop.
from collections import UserDict
from unittest.mock import ANY
class AnyDict(UserDict):
"""
Returns a dict that will use unittest.mock.ANY
as a value for keys that present in dict it is
going to be compared with for equality (or not equality),
but not in dict itself. It will also ensure that comparing
dict is just a dict, not OrderedDict or other subtype.
"""
def _fill_with_any(self, other):
missing_keys = set(other) - set(self.data)
self.data = {**self.data, **{key: ANY for key in missing_keys}}
def __eq__(self, other):
self._fill_with_any(other)
return super().__eq__(dict(other))
def __ne__(self, other):
self._fill_with_any(other)
return super().__ne__(dict(other))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment