mmpy_bot
mmpy_bot copied to clipboard
[Feature Request] Regex group name as arguments name
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."
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)
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?