def __init__(self, name, type_, none_value=None): """ ``name`` is the name of a field. ``type_`` is its type and ``none_value`` represents an empty value, callables are accepted as well. ``type_`` can be specified in both standard and simplified form, more on that read in chapter :ref:`type_specification`. ``none_value`` is used to replace ``None``, if field's ``none_value`` is ``None`` then that of its type is used. """ self.name = name self.type = TypeFactory(type_) self.none_value = none_value
def get(cls, type_): from pyws.functions.args.types import TypeFactory if len(type_) < 0: raise BadType( 'Element type (first element) is required for List type') type_[0] = TypeFactory(type_[0]) return ListOf(*type_)
class Field(object): """ A field combines a name, a type and a value that represents an empty value. """ def __init__(self, name, type_, none_value=None): """ ``name`` is the name of a field. ``type_`` is its type and ``none_value`` represents an empty value, callables are accepted as well. ``type_`` can be specified in both standard and simplified form, more on that read in chapter :ref:`type_specification`. ``none_value`` is used to replace ``None``, if field's ``none_value`` is ``None`` then that of its type is used. """ self.name = name self.type = TypeFactory(type_) self.none_value = none_value def get_value(self, data): try: return data[self.name] except KeyError: raise MissingFieldValue(self.name) def validate(self, value): try: return self.type.validate(value, self.none_value) except ValueError: raise WrongFieldValueType(self.name)
def ListOf(element_type, element_none_value=None): """ This function creates a list type with element type ``element_type`` and an empty element value ``element_none_value``. >>> from pyws.functions.args import Integer, ListOf >>> lst = ListOf(int) >>> issubclass(lst, List) True >>> lst.__name__ 'IntegerList' >>> lst.element_type == Integer True """ from pyws.functions.args.types import TypeFactory element_type = TypeFactory(element_type) return type(element_type.__name__ + 'List', (List,), { 'element_type': element_type, 'element_none_value': element_none_value})