Skip to content

Instantly share code, notes, and snippets.

@Deepwalker
Created May 17, 2018 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Deepwalker/2c01289d46e59ca528cb46ac7346ac15 to your computer and use it in GitHub Desktop.
Save Deepwalker/2c01289d46e59ca528cb46ac7346ac15 to your computer and use it in GitHub Desktop.
Something about matching for trafaret
import trafaret as t
groups = [
{'service': [{'guid': 'bla'}]},
{'service': []},
]
class Match(t.Trafaret):
def __init__(self, trafaret, first=True):
self.first = first
self.trafaret = t.ensure_trafaret(trafaret)
def transform(self, iterable, context=None):
res = []
for item in iterable:
try:
matched = self.trafaret(item)
if self.first:
return matched
else:
res.append(matched)
except t.DataError:
pass
if not res:
raise t.DataError('No match')
return res
tt = (
Match(t.Dict(service=Match(t.Dict(guid=t.Atom('bla')))))
& (lambda match: match['service'])
)
assert tt(groups) == {'guid': 'bla'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment