Cybrus Cybrus - 1 year ago 64
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:
elif regex.groups == 2:
elif regex.groups == 3:

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


Answer Source

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:


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

def listen_for_connections(command, amount):

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download