CD86
CD86

Reputation: 1089

generate keyword arguments from positional arguments in python

Given a function definition

def foo(model, evaluator):
    pass 

model = ...
evaluator = ...

and a call site like this

foo(model=model, evaluator=evaluator)

I would like to do only

foo(model, evaluator)

as to avoid repetition but then construct keyword arguments within foo for later passing onto **kwargs parameters.

The only way I can think of is

def foo(*args):
    **{str(arg): arg for arg in args}

is this ok?

Upvotes: 2

Views: 142

Answers (1)

shanecandoit
shanecandoit

Reputation: 621

You don't need the model=model bit. The arguments are positional, they match based on their order, not necessarily their name. Leave off the equals at the call site.

>>> def foo(bar, baz):
...     print('bar',bar,'baz',baz)
... 
>>> bar=2
>>> baz=3
>>> foo(bar,baz)
bar 2 baz 3

For more info on positional arguments: Positional argument v.s. keyword argument

If you want to just pass a dict to an object you can use the **arg syntax:

>>> def show_me(**m):
...     for k,v in m.items():
...             print(k,v)
>>> d={'x':2,'y':3}
>>> show_me(**d)
x 2
y 3

You have the call it with the double asterisk **d though:

>>> show_me(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: show_me() takes 0 positional arguments but 1 was given

Upvotes: 2

Related Questions