dgikmo dgikmo - 1 month ago 6
Python Question

How to set multiple function keywords at once, in Python 2?

all.

I was wondering if it was possible to set multiple keywords at once (via list?) in a function call.

For example, if you do:

foo, bar = 1, 2
print(foo, bar)


The output is
(1,2)
.

For the function

def printer(foo, bar)
print(foo,bar)


Is it possible to do something like:

printer([foo, bar] = [1,2])


where both keywords are being set with a list?

In particular, the reason why I ask is because I have a function that returns two variables,
scale
and
offset
:

def scaleOffset(...):
'stuff happens here

return [scale, offset]


I would like to pass both of these variables to a different function that accepts them as keywords, perhaps as a nested call.

def secondFunction(scale=None, offset=None):
'more stuff


So far I haven't found a way of doing a call like this:

secondFunction([scale,offset] = scaleOffset())

Answer

To pass args as a list

arg_list = ["foo", "bar"]
my_func(*arg_list)

To pass kwargs, use a dictionary

kwarg_dict = {"keyword": "value"}    
my_func(**kwarg_dict)