def from_dict(cls, json_dict): """ Convert a JSON dictionary to an instance of this class. :param json_dict: a JSON dictionary to parse. Dictionary with basic types (int, bool, dict, str, None, etc.) :return: an instance from this class or from a derived one from which it's called. :rtype: cls """ model = cls.get_model() # json_dict must be a a dictionary if not isinstance(json_dict, dict): raise exceptions.TypeException(dict, type(json_dict)) # By default, we set None for all expected keys default_json_dict = {key: None for key in model} default_json_dict.update(json_dict) cls.update_json_dict(json_dict) # Building this object # NB: We don't care about extra keys in provided dict, we just focus on expected keys, nothing more. kwargs = { key: parsing.to_type(default_json_dict[key], key_type) for key, key_type in model.items() } return cls(**kwargs)
def __init__(self, element_type, content=()): """ Initialize a typed sorted set. :param element_type: Expected type for values. :param content: (optional) Sequence of values to initialize sorted set with. """ if not is_sequence(content): raise exceptions.TypeException('sequence', type(content)) self.__type = element_type self.__list = [] for element in content: self.add(element)
def validate(self, element): if not isinstance(element, self.element_type): try: # Check if given element can be handled by element type. element_to_str = self.to_json(element) element_from_str = self.to_type(element_to_str) element_from_str_to_str = self.to_json(element_from_str) assert element_to_str == element_from_str_to_str except Exception: # Given element can't be handled, raise a type exception. raise exceptions.TypeException(self.element_type, type(element))
def validate(self, element): if not isinstance(element, self.element_type): raise exceptions.TypeException(self.element_type, type(element))
def validate(self, element): if not isinstance(element, self.seq_of_primitives): raise exceptions.TypeException(self.seq_of_primitives, type(element))
def validate(self, element): if not is_dictionary(element): raise exceptions.TypeException('dictionary', type(element)) for key, value in element.items(): self.key_type.validate(key) self.val_type.validate(value)
def validate(self, element): if not is_sequence(element): raise exceptions.TypeException('sequence', type(element)) for seq_element in element: self.element_type.validate(seq_element)