JBecker JBecker - 1 year ago 56
Python Question

Accessing all function argmuments

I have a function with 4 arguments and want to check those 4 arguments for something.
Currently I do it like this:

def function1(arg1, arg2, arg3, arg4):
arg1 = function2(arg1)
arg2 = function2(arg2)
arg3 = function2(arg3)
arg4 = function2(arg4)

def function2(arg):
arg = dosomething(arg)
return arg

I think this is not really a nice way to do it, so my idea is to do something like this:

def function1(arg1, arg2, arg3, arg4):
for arg in listOfArguments:
arg = function2(arg)

def function2(arg):
arg = checkSomething(arg)
return arg

Is there a way in Python to get a list of all the arguments passed to

Thanks for your help and ideas.

Answer Source

Since you have a set number of arguments just create an iterable out of them:

for arg in (arg1, arg2, arg3, arg4):
    # do stuff

If you don't mind your function being capable of being called with more args just use *args syntax:

def function1(*args):
    for arg in args:
        arg = function2(arg)

If you need to store the results for every invocation, it is better to change the for-loop in a list comprehension creating a list of the returned values. For example, given a function that takes a value and simply adds 2 to it:

def sum2(arg):
    return arg + 2

def function1(arg1, arg2, arg3, arg4):
    a1, a2, a3, a4 = [sum2(arg) for arg in (arg1, arg2, arg3, arg4)]
    print(a1, a2, a3, a4)

We create a list comprehension that takes every arg and supplies it to sum2 and then stores it as an entry in a list, then we unpack to a1,..,aN. The values now contain the results of the function calls:

function1(1, 2, 3, 4)
3, 4, 5, 6

In the previous examples (arg1, arg2, arg3, arg4) can always be replaced with args if you use the *args syntax when defining the function, the results will be similar.

Also, if you're more a fan of functional programming, you could always map the arguments to the function and save a few characters :-) :

def function1(arg1, arg2, arg3, arg4):
    a1, a2, a3, a4 = map(sum2, (arg1, arg2, arg3, arg4))
    print(a1, a2, a3, a4)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download