Guest User

Untitled

a guest
Jan 24th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1.  
  2. class aliasdict(dict):
  3.   def __init__(self, *args):
  4.     dict.__init__(self, args)
  5.     self._alias_table = {}
  6.  
  7.   def __getitem__(self, key):
  8.     if key in self._alias_table:
  9.       return dict.__getitem__(self, self._alias_table[key])
  10.     return dict.__getitem__(self, key)
  11.  
  12.   def __setitem__(self, key, value):
  13.     if isinstance(key, tuple):
  14.       dict.__setitem__(self, key[0], value)
  15.       for alias in key[1:]:
  16.         self._alias_table[alias] = key[0]
  17.     elif key in self._alias_table:
  18.       dict.__setitem__(self, self._alias_table[key], value)
  19.     else:
  20.       dict.__setitem__(self, key, value)
  21.  
  22.   def __contains__(self, key):
  23.     if key in self._alias_table:
  24.       return dict.__contains__(self, self._alias_table[key])
  25.     return dict.__contains__(self, key)
  26.  
  27. if __name__ == '__main__':
  28.   a = aliasdict()
  29.   a['foo', 'bar', 'quux'] = 42
  30.   print 'Test 1 passed' if a['bar'] == 42 else 'Test 1 failed'
  31.   print 'Test 2 passed' if a['quux'] == 42 else 'Test 2 failed'
  32.   print 'Test 3 passed' if a['foo'] == 42 else 'Test 3 failed'
  33.   print 'Test 4 passed' if 'bar' in a else 'Test 4 failed'
  34.   print 'Test 5 passed' if 'foo' in a else 'Test 5 failed'
  35.   print 'Test 6 passed' if not 'trololo' in a else 'Test 6 failed'
  36.  
  37.   a['quux'] = 3.14
  38.  
  39.   print 'Test 7 passed' if a['bar'] == 3.14 else 'Test 7 failed'
Add Comment
Please, Sign In to add comment