Skip to content

Instantly share code, notes, and snippets.

@pedro2555
Created January 3, 2019 22:13
Show Gist options
  • Save pedro2555/8644a7b3e3a88b0e19d2954547242ded to your computer and use it in GitHub Desktop.
Save pedro2555/8644a7b3e3a88b0e19d2954547242ded to your computer and use it in GitHub Desktop.
ptype.py
def search(regex):
"""Searches a given regex parameterized query into a dict
>>> @search('(?P<letter>[A-Z])?')
... def getletter(string):
... return string['letter']
...
>>> getletter('ABC')
('A', 'BC')
>>> getletter('0BC')
(None, '0BC')
"""
def decorator(parse_func):
"""Returns the search decorator"""
def func_wrapper(tail):
"""Returns the decorated search wrapper"""
match = re.search('^' + regex, tail.strip(), re.I | re.X)
if match is None:
return None, tail
# item = parse_func(match.groupdict())
item = match.groupdict(['type']
if item is not None:
tail = tail.strip()[match.end():]
return item, tail
return func_wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment