Dictionary Descriptors

R

Raymond Hettinger

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top