Dictionary Descriptors
Raymond Hettinger
python at rcn.com
Wed Mar 30 19:22:44 EDT 2011
On the python-ideas list, someone made a wild proposal to add
descriptors to dictionaries.
None of the respondents seemed to realize that you could (not should,
just could) already implement this using hooks already present in the
language. I'm posting an example here because I thought you all might
find it to be both interesting and educational.
For more details on how it works and how it relates to descriptors,
see http://mail.python.org/pipermail/python-ideas/2011-March/009657.html
Raymond
---- sample code ----
class MyDict(object):
def __init__(self, mapping):
self.mapping = mapping
def __getitem__(self, key):
value = self.mapping[key]
if hasattr(value, '__get__'):
print('Invoking descriptor on', key)
return value.__get__(key)
print('Getting', key)
return value
def __setitem__(self, key, value):
self.mapping[key] = value
class Property:
def __init__(self, getter):
self.getter = getter
def __get__(self, key):
return self.getter(key)
if __name__ == '__main__':
md = MyDict({})
md['x'] = 10
md['_y'] = 20
md['y'] = Property(lambda key: md['_'+key])
print(eval('x+y+1', {}, md))
---- output ----
Getting x
Invoking descriptor on y
Getting _y
31
More information about the Python-list
mailing list