trafaret — Validation atoms definition

exception trafaret.DataError(error=None, name=None, value=<object object>, trafaret=None)

Error with data preserve error can be a message or None if error raised in childs data can be anything

class trafaret.Trafaret

Base class for trafarets, provides only one method for trafaret validation failure reporting


Appends new converter to list.

check(value, context=None)

Common logic. In subclasses you need to implement check_value or check_and_return.

class trafaret.Call(fn)
>>> def validator(value):
...     if value != "foo":
...         return DataError("I want only foo!")
...     return 'foo'
>>> trafaret = Call(validator)
>>> trafaret
>>> trafaret.check("foo")
>>> extract_error(trafaret, "bar")
'I want only foo!'
class trafaret.Or(*trafarets)
>>> nullString = Or(String, Null)
>>> nullString
<Or(<String>, <Null>)>
>>> nullString.check(None)
>>> nullString.check("test")
>>> extract_error(nullString, 1)
{0: 'value is not a string', 1: 'value should be None'}
class trafaret.And(trafaret, other)

Will work over trafarets sequentially

class trafaret.Forward
>>> node = Forward()
>>> node << Dict(name=String, children=List[node])
>>> node
<Forward(<Dict(children=<List(<recur>)>, name=<String>)>)>
>>> node.check({"name": "foo", "children": []}) == {'children': [], 'name': 'foo'}
>>> extract_error(node, {"name": "foo", "children": [1]})
{'children': {0: 'value is not a dict'}}
>>> node.check({"name": "foo", "children": [                         {"name": "bar", "children": []}                      ]}) == {'children': [{'children': [], 'name': 'bar'}], 'name': 'foo'}
>>> empty_node = Forward()
>>> empty_node
>>> extract_error(empty_node, 'something')
'trafaret not set yet'
class trafaret.Any
>>> Any()
>>> (Any() >> ignore).check(object())
class trafaret.Null
>>> Null()
>>> Null().check(None)
>>> extract_error(Null(), 1)
'value should be None'
class trafaret.List(trafaret, min_length=0, max_length=None)
>>> List(Int)
>>> List(Int, min_length=1)
<List(min_length=1 | <Int>)>
>>> List(Int, min_length=1, max_length=10)
<List(min_length=1, max_length=10 | <Int>)>
>>> extract_error(List(Int), 1)
'value is not a list'
>>> List(Int).check([1, 2, 3])
[1, 2, 3]
>>> List(String).check(["foo", "bar", "spam"])
['foo', 'bar', 'spam']
>>> extract_error(List(Int), [1, 2, 1 + 3j])
{2: 'value is not int'}
>>> List(Int, min_length=1).check([1, 2, 3])
[1, 2, 3]
>>> extract_error(List(Int, min_length=1), [])
'list length is less than 1'
>>> List(Int, max_length=2).check([1, 2])
[1, 2]
>>> extract_error(List(Int, max_length=2), [1, 2, 3])
'list length is greater than 2'
>>> extract_error(List(Int), ["a"])
{0: "value can't be converted to int"}
class trafaret.Key(name, default=<object object>, optional=False, to_name=None, trafaret=None)

Helper class for Dict.

It gets name, and provides method extract(data) that extract key value from data through mapping get method. Key __call__ method yields (key name, result or DataError, [touched keys]) triples.

You can redefine get_data(data, default) method in subclassed Key if you want to use something other then .get(...) method.

Like this for the aiohttp MultiDict:

class MDKey(t.Key):
    def get_data(data, default):
        return data.get_all(, default)
class trafaret.Dict(*args, **trafarets)

Dict is a most complex trafaret that going with this library. The main difference from other common validation libs is that Dict trafaret does not know anything about actual keys. Every key that Dict works with knows itself how to get value from given mapping and if this will be one value or two or multi values.

So Dict cannot make any assumptions about whats going on other then contract with a key implementation. And we need to note, that any callable can be key, not only Key subclasses. So we need to look at the key contract:

key_instance(data: Mapping) -> Sequence[
name_to_store, result or DataError, Sequence[touched keys],


It is a bit complex, so let me explain it to you. Every key instance get this data that Dict trying to check. Then key will return one or multiple results and it is common for key to be generator.

Every result is three component tuple
1. Key for the result dict. For standard Key it is result key in case of successful check or original key name if there was an error 2. Result if keys trafaret check was successful or DataError instance otherwise 3. An iterable with all keys of original mapping that this key touched

With this tricky interface key in our lib can do anything you can imagine. Like work with MultiDicts, compare keys, get subdicts and check them independently from main one.

Why we need this third extra iterable with touched names? Because our Dict can check that all keys were consumed and what to do with extras.


  • Dict accepts keys as *args
  • if first argument to Dict is a dict then its keys will be merged with args keys and

this dict values must be trafarets. If key of this dict is a str, then Dict will create Key instance with this key as Key name and value as its trafaret. If key is a Key instance then Dict will call this key set_trafaret method.

allow_extra argument can be a list of keys, or ‘*’ for any, that will be checked against allow_extra_trafaret or Any.

ignore_extra argument can be a list of keys, or ‘*’ for any, that will be ignored.


Deprecated. will change in-place keys for given args or all keys if * in args.


Extends one Dict with other Dict Key`s or Key`s list, or dict instance supposed for Dict

class trafaret.Enum(*variants)
>>> trafaret = Enum("foo", "bar", 1) >> ignore
>>> trafaret
<Enum('foo', 'bar', 1)>
>>> trafaret.check("foo")
>>> trafaret.check(1)
>>> extract_error(trafaret, 2)
"value doesn't match any variant"
class trafaret.Tuple(*args)

Tuple checker can be used to check fixed tuples, like (Int, Int, String).

>>> t = Tuple(Int, Int, String)
>>> t.check([3, 4, '5'])
(3, 4, '5')
>>> extract_error(t, [3, 4, 5])
{2: 'value is not a string'}
>>> t
<Tuple(<Int>, <Int>, <String>)>
class trafaret.Atom(value)
>>> Atom('atom').check('atom')
>>> extract_error(Atom('atom'), 'molecule')
"value is not exactly 'atom'"
class trafaret.String(allow_blank=False, min_length=None, max_length=None)
>>> String()
>>> String(allow_blank=True)
>>> String().check("foo")
>>> extract_error(String(), "")
'blank value is not allowed'
>>> String(allow_blank=True).check("")
>>> extract_error(String(), 1)
'value is not a string'
>>> String(min_length=2, max_length=3).check('123')
>>> extract_error(String(min_length=2, max_length=6), '1')
'String is shorter than 2 characters'
>>> extract_error(String(min_length=2, max_length=6), '1234567')
'String is longer than 6 characters'
>>> String(min_length=2, max_length=6, allow_blank=True)
Traceback (most recent call last):
AssertionError: Either allow_blank or min_length should be specified, not both
>>> String(min_length=0, max_length=6, allow_blank=True).check('123')
class trafaret.Float(gte=None, lte=None, gt=None, lt=None)

Checks that value is a float. Or if value is a string converts this string to float

class trafaret.FloatRaw(gte=None, lte=None, gt=None, lt=None)

Tests that value is a float or a string that is convertable to float.

>>> Float()
>>> Float(gte=1)
>>> Float(lte=10)
>>> Float(gte=1, lte=10)
<Float(gte=1, lte=10)>
>>> Float().check(1.0)
>>> extract_error(Float(), 1 + 3j)
'value is not float'
>>> extract_error(Float(), 1)
>>> Float(gte=2).check(3.0)
>>> extract_error(Float(gte=2), 1.0)
'value is less than 2'
>>> Float(lte=10).check(5.0)
>>> extract_error(Float(lte=3), 5.0)
'value is greater than 3'
>>> Float().check("5.0")

alias of float

class trafaret.IntRaw(gte=None, lte=None, gt=None, lt=None)
>>> Int()
>>> Int().check(5)
>>> extract_error(Int(), 1.1)
'value is not int'
>>> extract_error(Int(), 1 + 1j)
'value is not int'

alias of int

class trafaret.Callable
>>> (Callable() >> ignore).check(lambda: 1)
>>> extract_error(Callable(), 1)
'value is not callable'
class trafaret.Bool
>>> Bool()
>>> Bool().check(True)
>>> Bool().check(False)
>>> extract_error(Bool(), 1)
'value should be True or False'
class trafaret.Type(type_)
>>> Type(int)
>>> Type[int]
>>> c = Type[int]
>>> c.check(1)
>>> extract_error(c, "foo")
'value is not int'

isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object’s type. The form using a tuple, isinstance(x, (A, B, …)), is a shortcut for isinstance(x, A) or isinstance(x, B) or … (etc.).

class trafaret.Subclass(type_)
>>> Subclass(type)
>>> Subclass[type]
>>> s = Subclass[type]
>>> s.check(type)
<type 'type'>
>>> extract_error(s, object)
'value is not subclass of type'

issubclass(C, B) -> bool

Return whether class C is a subclass (i.e., a derived class) of class B. When using a tuple as the second argument issubclass(X, (A, B, …)), is a shortcut for issubclass(X, A) or issubclass(X, B) or … (etc.).

class trafaret.Mapping(key, value)

Mapping gets two trafarets as arguments, one for key and one for value, like Mapping(t.Int, t.List(t.Str)).

class trafaret.StrBool
>>> extract_error(StrBool(), 'aloha')
"value can't be converted to Bool"
>>> StrBool().check(1)
>>> StrBool().check(0)
>>> StrBool().check('y')
>>> StrBool().check('n')
>>> StrBool().check(None)
>>> StrBool().check('1')
>>> StrBool().check('0')
>>> StrBool().check('YeS')
>>> StrBool().check('No')
>>> StrBool().check(True)
>>> StrBool().check(False)

Checks if dict has all given keys

>>> _dd(DictKeys(['a','b']).check({'a':1,'b':2,}))
"{'a': 1, 'b': 2}"
>>> extract_error(DictKeys(['a','b']), {'a':1,'b':2,'c':3,})
{'c': 'c is not allowed key'}
>>> extract_error(DictKeys(['key','key2']), {'key':'val'})
{'key2': 'is required'}
trafaret.guard(trafaret=None, **kwargs)

Decorator for protecting function with trafarets

>>> @guard(a=String, b=Int, c=String)
... def fn(a, b, c="default"):
...     '''docstring'''
...     return (a, b, c)
>>> fn.__module__ = None
>>> help(fn)
Help on function fn:

fn(*args, **kwargs)
    guarded with <Dict(a=<String>, b=<Int>, c=<String>)>


>>> fn("foo", 1)
('foo', 1, 'default')
>>> extract_error(fn, "foo", 1, 2)
{'c': 'value is not a string'}
>>> extract_error(fn, "foo")
{'b': 'is required'}
>>> g = guard(Dict())
>>> c = Forward()
>>> c << Dict(name=str, children=List[c])
>>> g = guard(c)
>>> g = guard(Int())
Traceback (most recent call last):
RuntimeError: trafaret should be instance of Dict or Forward
class trafaret.RegexpRaw(regexp, re_flags=0)

Check if given string match given regexp


Helper for complex trafarets, takes trafaret instance or class and returns trafaret instance

trafaret.extract_error(checker, *a, **kw)

Helper for tests - catch error and return it as dict


Stub to ignore value from trafaret Use it like:

>>> a = Int >> ignore
>>> a.check(7)
trafaret.catch(checker, *a, **kw)

Helper for tests - catch error and return it as dict

trafaret.catch_error(checker, *a, **kw)

Helper for tests - catch error and return it as dict