Last active
October 10, 2017 05:31
-
-
Save jnothman/d04dd9ae2ef4faf7914b0d9431ad62d6 to your computer and use it in GitHub Desktop.
A dict which raises a warning when some keys are looked up
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import warnings | |
from sklearn.utils.testing import assert_warns_message, assert_no_warnings | |
class DeprecationDict(dict): | |
"""A dict which raises a warning when some keys are looked up | |
Note, this does not raise a warning for __contains__ and iteration. | |
It also will raise a warning even after the key has been manually set by | |
the user. | |
""" | |
def __init__(self, *args, **kwargs): | |
self._deprecations = {} | |
super(DeprecationDict, self).__init__(*args, **kwargs) | |
def __getitem__(self, key): | |
if key in self._deprecations: | |
warn_args, warn_kwargs = self._deprecations[key] | |
warnings.warn(*warn_args, **warn_kwargs) | |
return super(DeprecationDict, self).__getitem__(key) | |
def get(self, key, default=None): | |
# dict does not implement it like this, hence it needs to be overridden | |
try: | |
return self[key] | |
except KeyError: | |
return default | |
def add_warning(self, key, *args, **kwargs): | |
"""Add a warning to be triggered when the specified key is read""" | |
self._deprecations[key] = (args, kwargs) | |
def test_deprecationdict(): | |
dd = DeprecationDict() | |
dd.add_warning('a', 'hello') | |
dd.add_warning('b', 'world', DeprecationWarning) | |
assert 1 == assert_warns_message(UserWarning, 'hello', dd.get, 'a', 1) | |
dd['a'] = 5 | |
dd['b'] = 6 | |
dd['c'] = 7 | |
assert 5 == assert_warns_message(UserWarning, 'hello', dd.__getitem__, 'a') | |
assert 6 == assert_warns_message(DeprecationWarning, 'world', | |
dd.__getitem__, 'b') | |
assert 7 == assert_no_warnings(dd.get, 'c') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment