Ejemplo n.º 1
0
def _resolve(thing, none_allowed=True):
    """
    Resolve an arbitrary object to a `Field` instance.

    Args:
        thing: anything to resolve to a `Field` instance.
        none_allowed (bool): if set then a thing of `None` will be resolved to a
            generic `Field`.

    Returns:
        Field: a field instance.
    """
    from serde.model import Model

    # If the thing is None then return a generic Field instance.
    if none_allowed and thing is None:
        return Field()
    # If the thing is a Field instance then thats great.
    elif isinstance(thing, Field):
        return thing
    # If the thing is a subclass of Field then attempt to create an instance.
    # This could fail the Field expects positional arguments.
    if is_subclass(thing, Field):
        return thing()
    # If the thing is a subclass of Model then create a Nested instance.
    if is_subclass(thing, Model):
        return Nested(thing)

    # If the thing is a built-in type that we support then create an Instance
    # with that type.
    try:
        return _FIELD_CLASS_MAP[thing]()
    except (KeyError, TypeError):
        pass

    raise TypeError('failed to resolve {!r} into a field'.format(thing))
Ejemplo n.º 2
0
def test_is_subclass():
    assert utils.is_subclass(5, int) is False
    assert utils.is_subclass(int, int) is True
Ejemplo n.º 3
0
        super(LengthMin, self).__call__(len(value))


class LengthMax(Max):
    """
    A validator that asserts the value's length is less than a maximum.

    Args:
        inclusive (bool): if this is set to `False` then the endpoint value will
            not be considered valid.
    """
    def __call__(self, value):
        super(LengthMax, self).__call__(len(value))


class LengthBetween(Between):
    """
    A validator that asserts the value's length is between two endpoints.

    Args:
        inclusive (bool): if this is set to `False` then the endpoint values
            will not be considered valid.
    """
    def __call__(self, value):
        return super(LengthBetween, self).__call__(len(value))


__all__ = [
    name for name, obj in globals().items() if is_subclass(obj, Validator)
]
Ejemplo n.º 4
0
    set: Set,
    str: Str,
    tuple: Tuple,
    # Collections
    collections.deque: Deque,
    collections.OrderedDict: OrderedDict,
    # Datetimes
    datetime.datetime: DateTime,
    datetime.date: Date,
    datetime.time: Time,
    # Others
    uuid.UUID: Uuid,
}

try:
    _FIELD_CLASS_MAP[basestring] = BaseString
except NameError:
    pass

try:
    _FIELD_CLASS_MAP[long] = Long
except NameError:
    pass

try:
    _FIELD_CLASS_MAP[unicode] = Unicode
except NameError:
    pass

__all__ = [name for name, obj in globals().items() if is_subclass(obj, Field)]
Ejemplo n.º 5
0
Archivo: tags.py Proyecto: grgi/serde
        """
        variant = model.__class__
        d = OrderedDict([(self.tag, self._serialize(variant)),
                         (self.content, d)])
        return d

    def _deserialize_with(self, model, d):
        """
        Deserialize the model variant from an adjacently tagged dictionary.
        """
        try:
            tag = d[self.tag]
        except KeyError:
            raise ValidationError('missing data, expected tag {!r}'.format(
                self.tag))

        try:
            content = d[self.content]
        except KeyError:
            raise ValidationError('missing data, expected content {!r}'.format(
                self.content))

        model.__class__ = self._deserialize(tag)

        return model, content


__all__ = [
    name for name, obj in globals().items() if utils.is_subclass(obj, Tag)
]