Advertisement
Guest User

Untitled

a guest
May 26th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.50 KB | None | 0 0
  1. import collections
  2.  
  3. class CustomUserDict(collections.UserDict):
  4.  
  5. def __missing__(self, key):
  6. if isinstance(key, str):
  7. raise KeyError(key)
  8. return self[str(key)]
  9.  
  10. def __contains__(self, key):
  11. return str(key) in self.data
  12.  
  13. def __setitem__(self, key, item):
  14. self.data[str(key)] = item
  15.  
  16.  
  17. if __name__ == '__main__':
  18.  
  19. d = CustomUserDict({1:"one", 2:"two", 3:"three"})
  20.  
  21. print(d[1])
  22. print(d['1'])
  23. print(d[4]) # raises KeyError
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement