relief

class relief.Element(value=Unspecified)

Base class for elements. An element allows you to describe Python objects.

This class specifically defines a basic interface for elements and provides some generally useful methods.

strict = False

When True unserialize() should not attempt to unserialize raw values that are instances of native_type and return NotUnserializable instead.

native_type

The “native” type represented by this element.

alias of NoneType

default = Unspecified

The default value that should be used for this element. This value will be used if not initial value is given.

default_factory = Unspecified

A callable that is called with the element, which should be used to produce the default value that is used if no initial value is given. default takes precedence.

properties = {}

A dictionary whose contents are inherited by subclasses, which should be used for application-specific information associated with an element.

classmethod using(**kwargs)

Returns a clone of the class whose attributes have been overwritten with the given keyword arguments.

classmethod validated_by(validators)

Returns a clone of the class that is also validated by the given iterable of validators.

classmethod with_properties(**properties)

Returns a clone of the class whose properties contain the given properties in addition to the ones inherited from this one.

classmethod unserialize(raw_value)

Tries to unserialize the given raw_value and returns an object whose type matches the type described by the element.

is_valid = None

Defines the validation state of the element, may be one of the following values:

None
The element has not been validated, yet.
True
The element is valid.
False
The element is not valid.
errors = None

A list that is supposed to be populated with unicode strings by a validator as an explanation of why the element is invalid.

raw_value = None

The concrete value this element represents. May also be Unspecified if the value has not been set. This may be helpful to look at if value is NotUnserializable.

value = None

The unserialized concrete value this element represents. May also be Unspecified if the value has not been set or NotUnserializable if unserialize() was unable to unserialize the value.

set(raw_value)

Sets raw_value with the given raw_value and sets value to the unserialized form of raw_value if applicable.

validate(context=None)

Returns True when the element is valid and False otherwise, and sets is_valid to the returned value.

If any validators have been defined for this element, each validator is called with the element and the given context (which defaults to None). If any validator returns False, the element will be considered invalid.

If no validators have been defined, the element will be considered invalid if value is Unspecified or NotUnserializable.

Scalars

class relief.Boolean(value=Unspecified)

Represents a bool().

Unlike other elements this does not call bool() on an object to unserialize a raw value, instead if the raw value is one of u"True" or b"True" it will unserialize to True and if the raw value is one of u"False" or b"False" it will unserialize to False.

class relief.Integer(value=Unspecified)

Represents an int().

Unserializes unicode and byte strings that represent integers in base 10 as raw values:

>>> from relief import Integer
>>> element = Integer()
>>> element.set(u"1")
>>> element.value
1
>>> element.set(b"1")
>>> element.value
1
class relief.Float(value=Unspecified)

Represents a float().

Unserializes unicode and byte strings like Integer.

class relief.Complex(value=Unspecified)

Represents a complex().

Unserializes unicode and byte strings like Integer.

class relief.Unicode(value=Unspecified)

Represents a unicode() string.

Accepts any byte string that is encoded using the default encoding or which ever encoding has been set as encoding:

>>> from relief import Unicode
>>> element = Unicode()
>>> element.set(u"Hello, World!")
>>> element.value
u"Hello, World!"
>>> element.set(b"Hello, World!")
>>> element.value
u"Hello, World!"
native_type

alias of unicode

encoding = None

The encoding used to decode raw values, can be set with using() and defaults to the default encoding, which is usually ASCII or UTF-8 depending on whether you use 2.x or 3.x.

class relief.Bytes(value=Unspecified)

Represents a bytes() string.

Accepts any unicode string that can be decoded using the default encoding:

>>> from relief import Bytes
>>> element = Bytes()
>>> element.set(b"Hello, World!")
>>> element.value
b"Hello, World!"
>>> element.set(u"Hello, World!")
>>> element.value
b"Hello, World!"
native_type

alias of str

Sequences

class relief.Tuple(value=Unspecified)

Represents a tuple().

You cannot use Tuple directly, as it does not know what kind of schemas it contains or which length it has, both fundamental properties of a tuple.

In order to use Tuple you have to derive Tuple schema that knows about the length and the contents with of(). You do this by simply calling of() with as many different schemas as the tuple is supposed to be long, each schema responding to the contents you want the contents to be:

>>> from relief import Tuple, Integer, Unicode
>>> UsableTuple = Tuple.of(Integer, Unicode)

UsableTuple would be one such derived schema, that defines a tuple with a length of 2, whose first item is an integer and whose second item is a unicode string.

The derived schema can then be used like any other schema:

>>> element = UsableTuple()
>>> element.set((1, u"Hello, World!"))
>>> element.value
(1, u"Hello, World!")

Tuple will successfully unserialize any iterable that yields as many times as the tuple is long. However should any of those schemas contained within the tuple fail to unserialize a raw value yielded by an iterable, value will be NotUnserializable:

>>> element.set((u"foobar", u"Hello, World!"))
>>> element.value
NotUnserializable

Furthermore Tuple elements inherit from tuple(), you can perform all operations on them you can on any other tuple():

>>> element = Tuple.of(Integer, Unicode)((1, u"Hello, World!"))
>>> element.count(1)
1
>>> element.index(u"Hello, World!")
1

Any operation that returns the contents of the element in some fashion, will not return a value but an element.

native_type

alias of tuple

classmethod of(*schemas)

Returns a new Tuple class whose contents are defined by the given schemas.

class relief.List(value=Unspecified)

Represents a list().

List represents a homogeneous list of values, in order to define what kind of values it contains and to actually use List you have to derive a specific List schema using of():

>>> from relief import List, Integer
>>> IntegerList = List.of(Integer)

List will successfully unserialize any iterable that yields 0 or more objects, that can be unserialized by the schema defining the contents of the list:

>>> element = IntegerList()
>>> element.set([])
>>> element.value
[]
>>> element.set([1, 2, 3])
>>> element.value
[1, 2, 3]
>>> element.set(["foobar", 2, 3])
>>> element.value
NotUnserializable
native_type

alias of list

Mappings

class relief.Dict(value=Unspecified)

Represents a dict.

Dict maps homogenous keys to homogeneous values, in order to use it you have to derive a Dict schema using of() specifying the schemas used for keys and values:

>>> from relief import Dict, Unicode, Integer
>>> UnicodeIntegerDict = Dict.of(Unicode, Integer)

The derived schema will behave like other container schemas, anything you can pass to dict as positional argument can be used as a raw value.

>>> element = UnicodeIntegerDict()
>>> element.set({u"foo": 1})

Dict is a subclass of dict, so all non-mutating operations you can perform on a dict you can also perform on a Dict. Any operation that return objects stored within the dictionary will return the element not the value.

native_type

alias of dict

class relief.OrderedDict(value=Unspecified)

Represents a collections.OrderedDict.

See Dict for more information.

native_type

alias of OrderedDict

class relief.Form(value=Unspecified)

Represents a dict that maps a fixed set of keys to heterogeneous values.

In order to use Form you need to derive a Form schema that knows what kind of keys it contains and what schemas corresponding to those keys are:

>>> from relief import Form, Integer, Unicode
>>> Something = Form.of({
...     "foo": Integer,
...     "bar": Unicode
... })

Something is such a derived schema, defined to have to keys foo and bar with an integer and a unicode string as values.

Instead of passing a dict to of() you can also use an collections.OrderedDict this way you can enforce an order that will be respected during iteration over the form. It will have no effect on what is considered a valid value.

Instead of using of() to derive schemas Form you can also subclass Form and define the contents declaratively:

>>> class Something(Form):
...     foo = Integer
...     bar = Unicode

This is almost equivalent to the example using of() above, the difference being that the order will be remembered, the same way as it would have been, if collections.OrderedDict would have been used in the of() example.

Anything that can be passed as a positional argument to dict can be used as a raw value:

>>> element = Something()
>>> element.set([("foo", 1), ("bar", u"spam")])
>>> element.value
OrderedDict([('foo', 1), ('bar', u'spam')])

It is quite common to have very specific validation requirements for values in forms. In order to conveniently handle this case, you can add methods with names like validate_{key} where key is the key under which the value is reachable:

class Something(Form):
    foo = Integer

    def validate_foo(self, element, context):
        # Perform validation on `foo` value.
        ...

New in version 0.2: Added the ability to validate values with validate_{key} methods.

native_type

alias of dict

Constants

relief.Unspecified = Unspecified

A constant that describes unspecified values.

relief.NotUnserializable = NotUnserializable

A constant that describes values that could not be unserialized.

Project Versions

Table Of Contents

Previous topic

Tutorial

Next topic

relief.validation

This Page