Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 function1?

Thanks for your help and ideas.

like image 603
JBecker Avatar asked Nov 27 '25 00:11

JBecker


1 Answers

Since you have a set number of arguments just create an iterable out of them, for example, wrap the argument names in a tuple literal:

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)

which then exposes the arguments with which the function was invoked as a tuple which can be iterated over.

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 add2(arg):
    return arg + 2

def function1(arg1, arg2, arg3, arg4):
    a1, a2, a3, a4 = [add2(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 add2 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.


As an addendum, if you're more a fan of functional programming, you could always map the arguments to the function and save a few characters :-). I'll add a *args definition of function1 this time:

def function1(*args):
    a1, a2, a3, a4 = map(add2, args)
    print(a1, a2, a3, a4)

Same result.

like image 197
Dimitris Fasarakis Hilliard Avatar answered Nov 29 '25 15:11

Dimitris Fasarakis Hilliard