Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class aliasdict(dict):
- def __init__(self, *args):
- dict.__init__(self, args)
- self._alias_table = {}
- def __getitem__(self, key):
- if key in self._alias_table:
- return dict.__getitem__(self, self._alias_table[key])
- return dict.__getitem__(self, key)
- def __setitem__(self, key, value):
- if isinstance(key, tuple):
- dict.__setitem__(self, key[0], value)
- for alias in key[1:]:
- self._alias_table[alias] = key[0]
- elif key in self._alias_table:
- dict.__setitem__(self, self._alias_table[key], value)
- else:
- dict.__setitem__(self, key, value)
- def __contains__(self, key):
- if key in self._alias_table:
- return dict.__contains__(self, self._alias_table[key])
- return dict.__contains__(self, key)
- if __name__ == '__main__':
- a = aliasdict()
- a['foo', 'bar', 'quux'] = 42
- print 'Test 1 passed' if a['bar'] == 42 else 'Test 1 failed'
- print 'Test 2 passed' if a['quux'] == 42 else 'Test 2 failed'
- print 'Test 3 passed' if a['foo'] == 42 else 'Test 3 failed'
- print 'Test 4 passed' if 'bar' in a else 'Test 4 failed'
- print 'Test 5 passed' if 'foo' in a else 'Test 5 failed'
- print 'Test 6 passed' if not 'trololo' in a else 'Test 6 failed'
- a['quux'] = 3.14
- print 'Test 7 passed' if a['bar'] == 3.14 else 'Test 7 failed'
Add Comment
Please, Sign In to add comment