Cybrus Cybrus - 1 month ago 6
Python Question

An elegant way of inserting multiple arguments

I have this dictionary:

local_commands_dict = {
r"\b(listen)\b\s(\d+)": listen_for_connections
}


Which contains a regex to match as key and a method variable as value.
I am using the following code to navigate user input, into a command from the dictionary:

for cmd in local_commands_dict:
regex = re.compile(cmd)
match = regex.match(data)
if match is not None:
if regex.groups == 1:
local_commands_dict[cmd]()
elif regex.groups == 2:
local_commands_dict[cmd](match.group(2))
elif regex.groups == 3:
local_commands_dict[cmd](match.group(2),match.group(3))
break


Where
data
is the user input. Is there any nicer way to navigate between the different amount of arguments? There must be, it's Python.

Thanks!

Answer

In general you can pass a variable number of arguments using *:

args = (1, 2)
func(*args)  # Same as func(1, 2)

You can call .groups() to retrieve all arguments, and pass them:

local_commands_dict[cmd](*match.groups())

If you give names to your groups, then this works too:

def listen_for_connections(command, amount):
    pass

local_commands_dict = {
    r"\b(?P<command>listen)\b\s(?P<amount>\d+)": listen_for_connections
}

local_commands_dict[cmd](**match.groupdict())

Now the match for the 'command' group is passed as the 'command' argument, and 'amount' as 'amount'. This way the order of arguments of the function and the order of groups in the regex don't need to be the same, but instead the names must be.