Last active
March 1, 2019 00:22
-
-
Save pj/114c629bfdec82b9a00b09c0d52818ea to your computer and use it in GitHub Desktop.
This file contains 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
# Unlike MutableMapping, dict has it's own implementation of get() that doesn't use __getitem__ underneath. This will cause your subclass to return None unexpectedly, unless you don't implement get() as well. Probably better to just subclass MutableMapping :-). | |
# example code: | |
def test_dict_subclass_get_method(): | |
import collections | |
# WORKS: class Hello(collections.MutableMapping): | |
class Hello(dict): | |
def __init__(self, underlying): | |
super(Hello, self).__init__() | |
self._underlying = underlying | |
def __len__(self): | |
return len(self._underlying) | |
def __iter__(self): | |
return self._underlying.__iter__() | |
# def get(self, key, default): | |
# return self._underlying.get(key, default) | |
def __getitem__(self, key): | |
return self._underlying[key] | |
def __setitem__(self, key, value): | |
self._underlying[key] = value | |
def __delitem__(self, key): | |
del self._underlying[key] | |
underlying = {} | |
hello = Hello(underlying) | |
hello['world'] = 'foo' | |
assert hello['world'] == 'foo' | |
assert hello.get('world') == 'foo' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment