Created
December 9, 2011 03:00
-
-
Save cwvh/1449952 to your computer and use it in GitHub Desktop.
Clean code with better named captures.
This file contains 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
"""`namedmatch` mimics `re.match` but also creates attributes based on the | |
values of the named captures. | |
Example | |
>>> string = 'foo bar baz' | |
>>> match = namedmatch(r'(?P<start>\w+) (?P<end>\w+)', string) | |
>>> print match.start | |
"foo" | |
>>> print match.end | |
"bar" | |
>>> print match | |
namedmatch({'start': 'foo', 'end': 'bar'}) | |
""" | |
from collections import namedtuple | |
import re | |
def namedmatch(pattern, string, flags=0, matcher=re.match): | |
match = matcher(pattern, string, flags) | |
if match is None: | |
return None | |
groupdict = match.groupdict() | |
NamedMatch = namedtuple('namedmatch', groupdict.iterkeys()) | |
return NamedMatch(*groupdict.itervalues()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment