validate arbitrary data structures in python
Python JavaScript HTML
Switch branches/tags
Nothing to show
#67 Compare This branch is 212 commits ahead of piranha:master.
Latest commit 56d2ce7 Jun 24, 2017 @Deepwalker add gitter chat
Failed to load latest commit information.
docs remove entrypoint magic May 12, 2017
js rename all contracts to trafarets Jan 26, 2012
samples Fixed Mar 12, 2012
tests Remove __bool__ from DataError. It seems that Errors must not be False Jun 11, 2017
trafaret Remove __bool__ from DataError. It seems that Errors must not be False Jun 11, 2017
.gitignore add subclass trafaret Aug 3, 2016
.gitmodules js contracts initial May 26, 2011
.travis.yml Add .travis.yml Dec 30, 2014
LICENSE.txt Add BSD license file Jan 26, 2015 Add BSD license file Jan 26, 2015
README.rst add gitter chat Jun 24, 2017
circle.yml fix contrib.object_id Mar 15, 2017 continue entry_points remove May 12, 2017



Build status Gitter Downloads Downloads

Read The Docs hosted documentation <> or look to the docs/api/intro.rst for start.

Trafaret is rigid and powerful lib to work with foreign data, configs etc. It provides simple way to check anything, and convert it accordingly to your needs.

It have shortcut syntax and ability to express anything that you can code:

>>> from trafaret.constructor import construct
>>> validator = construct({'a': int, 'b': [str]})
>>> validator({'a': 5, 'b': ['lorem', 'ipsum']})
{'a': 5, 'b': ['lorem', 'ipsum']}

>>> validator({'a': 5, 'b': ['gorky', 9]})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/mkrivushin/w/trafaret/trafaret/", line 204, in __call__
    return self.check(val)
  File "/Users/mkrivushin/w/trafaret/trafaret/", line 144, in check
    return self._convert(self.check_and_return(value))
  File "/Users/mkrivushin/w/trafaret/trafaret/", line 1105, in check_and_return
    raise DataError(error=errors, trafaret=self)
trafaret.DataError: {'b': DataError({1: DataError(value is not a string)})}

For simple example what can be done:

import datetime
import trafaret as t

date = t.Dict(year=t.Int, month=t.Int, day=t.Int) >> (lambda d: datetime.datetime(**d))
assert date.check({'year': 2012, 'month': 1, 'day': 12}) == datetime.datetime(2012, 1, 12)

Work with regex:

>>> c = t.String(regex=r'^name=(\w+)$') >> (lambda m: m.groups()[0])
>>> c.check('name=Jeff')

Rename dict keys:

>>> c = t.Dict(t.Key('uNJ') >> 'user_name': t.String})
>>> c.check({'uNJ': 'Adam'})
{'user_name': 'Adam'}

Arrow date checking:

import arrow

def check_datetime(str):
        return arrow.get(str).naive
    except arrow.parser.ParserError:
        return t.DataError('value is not in proper date/time format')

Yes, you can write trafarets that simple.

Related projects

Trafaret Config

Trafaret Validator