Permalink
Browse files

Added Tuple

  • Loading branch information...
1 parent a867e12 commit 564f0ad8c24dc9065d78d988fa3abf75a000ad37 @Deepwalker committed May 29, 2012
Showing with 46 additions and 1 deletion.
  1. +6 −0 CHANGES.rst
  2. +1 −1 setup.py
  3. +39 −0 trafaret/__init__.py
View
@@ -1,6 +1,12 @@
Changes
=======
+2012-05-30
+----------
+
+Renamed methods to ``check_value`` and ``check_and_return``.
+Added ``Tuple`` trafaret.
+
2012-05-28
----------
View
@@ -10,7 +10,7 @@ def read(fname):
setupconf = dict(
name = 'trafaret',
- version = '0.4.6',
+ version = '0.4.7',
license = 'BSD',
url = 'https://github.com/Deepwalker/trafaret/',
author = 'Barbuza, Deepwalker, nimnull',
View
@@ -708,6 +708,45 @@ def __repr__(self):
return r
+class Tuple(Trafaret):
+ """
+ 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>)
+ """
+
+ def __init__(self, *args):
+ self.trafarets = list(map(self._trafaret, args))
+ self.length = len(self.trafarets)
+
+ def check_and_return(self, value):
+ try:
+ value = tuple(value)
+ except TypeError:
+ self._failure('value must be convertable to tuple')
+ if len(value) != self.length:
+ self._failure('value must contain exact %s items' % self.length)
+ result = []
+ errors = {}
+ for idx, (item, trafaret) in enumerate(zip(value, self.trafarets)):
+ try:
+ result.append(trafaret.check(item))
+ except DataError as err:
+ errors[idx] = err
+ if errors:
+ self._failure(errors)
+ return tuple(result)
+
+ def __repr__(self):
+ return '<Tuple(' + ', '.join(repr(t) for t in self.trafarets) + ')'
+
+
class Key(object):
"""

0 comments on commit 564f0ad

Please sign in to comment.