José Luis
José Luis

Reputation: 889

Pass keyword arguments as required arguments in Python

I have, for example, 3 functions, with required arguments (some arguments are shared by the functions, in different order):

def function_one(a,b,c,d,e,f):
   value = a*b/c ...
   return value

def function_two(b,c,e):
   value = b/e ..
   return value

def function_three(f,a,c,d):
   value = a*f ...
   return value

If I have the next dictionary:

argument_dict = {'a':3,'b':3,'c':23,'d':6,'e':1,'f':8}

Is posible to call the functions in this way??:

value_one = function_one(**argument_dict)
value_two = function_two (**argument_dict)
value_three = function_three (**argument_dict)

Upvotes: 3

Views: 416

Answers (2)

zom-pro
zom-pro

Reputation: 1649

I assume what you're trying to do is to create a function with an undefined number of arguments. You can do this by using args (arguments) or kwargs (key word arguments kind of foo='bar') style so for example:

for arguments

def f(*args): print(args)

f(1, 2, 3)
(1, 2, 3)`

then for kwargs

def f2(**kwargs): print(kwargs)

f2(a=1, b=3)
{'a': 1, 'b': 3}

Let's try a couple more things.

def f(my_dict): print (my_dict['a'])

f(dict(a=1, b=3, c=4))
1

It works!!! so, you could do it that way and complement it with kwargs if you don't know what else the function could receive.

Of course you could do:

argument_dict = {'a':1, 'b':3, 'c':4}
f(argument_dict)
1

So you don't have to use kwargs and args all the time. It all depends the level of abstraction of the object you're passing to the function. In your case, you're passing a dictionary so you can handle that guy without only.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599460

Not the way you have written those functions, no: they are not expecting the extra arguments so will raise a TypeError.

If you define all the functions as also expecting **kwargs, things will work as you want.

Upvotes: 4

Related Questions