Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created September 10, 2013 05:19
Show Gist options
  • Save thomasballinger/6505280 to your computer and use it in GitHub Desktop.
Save thomasballinger/6505280 to your computer and use it in GitHub Desktop.
Currying dictionary assignment in Python
class ProxiedGetitem(object):
"""Dictionary whose keys are 2-element tuples; if one element tuple used,
the __getitem__ method is curried
>>> d = ProxiedGetitem()
>>> d # doctest: +ELLIPSIS
<__main__.ProxiedGetitem object at 0x...>
>>> d[1,2] = 'a'
>>> d[1,2]
'a'
>>> d[1] # doctest: +ELLIPSIS
<"Curried" getitem object for <__main__.ProxiedGetitem object at 0x...>>
>>> d[1][2]
'a'
>>> d[1][2] = 'b'
>>> d[1,2]
'b'
"""
def __init__(self):
self.d = {}
def __getitem__(self, key):
if isinstance(key, tuple) and len(key) == 2:
return self.d[key]
else:
return CurriedGetitem(self, key)
def __setitem__(self, key, value):
if isinstance(key, tuple) and len(key) == 2:
self.d[key] = value
else:
raise KeyError
class CurriedGetitem(object):
def __init__(self, parent, index):
self.parent = parent
self.first_index = index
def __repr__(self):
return '<"Curried" getitem object for '+repr(self.parent)+'>'
def __getitem__(self, key):
return self.parent[(self.first_index, key)]
def __setitem__(self, key, value):
self.parent[(self.first_index, key)] = value
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment