mmpy_bot icon indicating copy to clipboard operation
mmpy_bot copied to clipboard

[Feature Request] Regex group name as arguments name

Open sheiun opened this issue 5 years ago • 2 comments

Current Behavior

@response_to(r"(?P<first_name>.+) (?P<last_name>.+)")
def get_name(message, first_name, last_name):
    message.reply(f"Your name is {first_name} {last_name}.")
    >>> "Your name is Lena Smith."

or

@response_to(r"(?P<first_name>.+) (?P<last_name>.+)")
def get_name(message, *args):
    message.reply(f"Your name is {args[0]} {args[1]}.")
    >>> "Your name is Lena Smith."

or

@response_to(r"(?P<first_name>.+) (?P<last_name>.+)")
def get_name(message, *args):
    keys = ["first_name", "last_name"]
    kwargs = dict(zip(keys, args))
    message.reply(f"Your name is {kwargs["first_name"]} {kwargs ["last_name"]}.")
    >>> "Your name is Lena Smith."

Expected Behavior

@response_to(r"(?P<first_name>.+) (?P<last_name>.+)")
def get_name(message, **kwargs):
    message.reply(f"Your name is {kwargs['first_name']} {kwargs['last_name']}.")
    >>> "Your name is Lena Smith."

sheiun avatar Oct 27 '19 11:10 sheiun

Some partial code that could be used to implement this. This permits extracting args and kwargs from a regexp.

named_args = set(matcher.groupindex.values())
groups = list([group
               for i, group in enumerate(match.groups())
               if group != "" and i not in named_args])
namegroups = {k: v for k, v in match.groupdict() if v != ""}

instead of:

groups = list([group for group in match.groups() if group != ""])

However, there are still edge cases such as: r"(?P<first_name>.+) (.+) (?P<last_name>.+)" where combining position and name based arguments will cause problems. The function would need a signature such as def hello(middle_names, first_name, last_name)

unode avatar Sep 13 '22 21:09 unode

Revisiting this issue, I don't think we can implement the above without properly handling the edge cases mentioned. This would actually make the code quite more complex.

If anything, we need a more sophisticated parser for complex cases. parsy has proved reliable on my personal uses. Something for another pull-request/improvement.

I would vote to close this as wontfix. @attzonko your take on it?

unode avatar May 09 '23 09:05 unode