-
-
Save itnow/a23b4f59c0d9b2e1fd177c80fd7f9060 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