Guest User

Untitled

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