def get(self, key): """return a value if present; otherwise None.""" keyfilt = dict_key_to_raw(key, self.d_field.d_keytype) data = self.d_data.get(keyfilt) if data is not None: return BoundCompoundValue(self.d_field.d_value, data) return None
def get(self, key: TKey, default: Optional[T] = None) -> Optional[T]: """Get a value if present, or a default otherwise.""" keyfilt = dict_key_to_raw(key, self._keytype) if keyfilt not in self.d_data: return default typedval: T = self.d_field.d_value.filter_output(self.d_data[keyfilt]) return typedval
def add(self, key: TKey) -> TCompound: """Add an entry into the dict, returning it. Any existing value is replaced.""" keyfilt = dict_key_to_raw(key, self.d_field.d_keytype) # Push the entity default into data and then let it fill in # any children/etc. self.d_data[keyfilt] = (self.d_field.d_value.filter_input( self.d_field.d_value.get_default_data(), error=True)) return BoundCompoundValue(self.d_field.d_value, self.d_data[keyfilt])
def filter_input(self, data: Any, error: bool) -> Any: # If we were passed a BoundDictField, operate on its raw values if isinstance(data, BoundDictField): data = data.d_data if not isinstance(data, dict): if error: raise TypeError('dict value expected') logging.error('Ignoring non-dict data for %s: %s', self, data) data = {} data_out = {} for key, val in data.items(): # For enum keys, make sure its a valid enum. if issubclass(self._keytype, Enum): # Our input data can either be an enum or the underlying type. if isinstance(key, self._keytype): key = dict_key_to_raw(key, self._keytype) # key = key.value else: try: _enumval = dict_key_from_raw(key, self._keytype) # _enumval = enum_by_value(self._keytype, key) except Exception as exc: if error: raise ValueError( f'No enum of type {self._keytype}' f' exists with value {key}') from exc logging.error('Ignoring invalid key type for %s: %s', self, data) continue # For all other keys we can check for exact types. elif not isinstance(key, self._keytype): if error: raise TypeError( f'Invalid key type; expected {self._keytype},' f' got {type(key)}.') logging.error('Ignoring invalid key type for %s: %s', self, data) continue data_out[key] = self.d_value.filter_input(val, error=error) return data_out
def __delitem__(self, key: TKey) -> None: keyfilt = dict_key_to_raw(key, self.d_field.d_keytype) del self.d_data[keyfilt]
def __contains__(self, key: TKey) -> bool: keyfilt = dict_key_to_raw(key, self.d_field.d_keytype) return keyfilt in self.d_data
def __getitem__(self, key): keyfilt = dict_key_to_raw(key, self.d_field.d_keytype) return BoundCompoundValue(self.d_field.d_value, self.d_data[keyfilt])
def __setitem__(self, key: TKey, value: T) -> None: keyfilt = dict_key_to_raw(key, self._keytype) self.d_data[keyfilt] = self.d_field.d_value.filter_input(value, error=True)
def __getitem__(self, key: TKey) -> T: keyfilt = dict_key_to_raw(key, self._keytype) typedval: T = self.d_field.d_value.filter_output(self.d_data[keyfilt]) return typedval