Created
May 17, 2018 13:59
-
-
Save Deepwalker/2c01289d46e59ca528cb46ac7346ac15 to your computer and use it in GitHub Desktop.
Something about matching for trafaret
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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