DeaD_EyE

RangeDict

Feb 16th, 2020
105
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. I got this Idea from here: https://github.com/Superbird11/ranges
  3. """
  4.  
  5. from collections import UserDict
  6.  
  7.  
  8. class RangeDict(UserDict):
  9.    
  10.     def _check(self, key):
  11.         if isinstance(key, range):
  12.             return key
  13.         if isinstance(key, float):
  14.             try:
  15.                 key = int(key)
  16.             except ValueError:
  17.                 raise ValueError("Key must be an integer or float")
  18.             else:
  19.                 return key
  20.        
  21.     def _get_key(self, key):
  22.         for the_range in self._get_all_keys(key):
  23.             return the_range
  24.         else:
  25.             raise KeyError("Value was not found in ranges")
  26.    
  27.     def _get_all_keys(self, key):
  28.         self._check(key)
  29.         return [the_range for the_range in self.keys() if key in the_range]
  30.        
  31.     def __getitem__(self, key):
  32.         the_range = self._get_key(key)
  33.         return super().__getitem__(the_range)
  34.        
  35.     def __setitem__(self, key, value):
  36.         if not isinstance(key, range):
  37.             raise ValueError('Only range is allowed as key')
  38.         super().__setitem__(key, value)
  39.    
  40.     def __delitem__(self, key):
  41.         the_range = self._get_key(key)
  42.         super().__delitem__(the_range)
  43.        
  44.     def get(self, key, default=None):
  45.         try:
  46.             value = self[key]
  47.         except KeyError:
  48.             return default
  49.         else:
  50.             return value
  51.    
  52.     def get_many(self, key):
  53.         return [super(RangeDict, self).__getitem__(r) for r in self._get_all_keys(key)]
  54.        
  55.     def pop(self, key):
  56.         return super().pop(key)
  57.    
  58.     def popitem(self, key):
  59.         return self._get_key(key), self.pop(key)
RAW Paste Data