Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass keyword arguments as required arguments in Python

Tags:

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)
like image 566
José Luis Avatar asked Jun 03 '26 12:06

José Luis


2 Answers

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.

like image 126
Daniel Roseman Avatar answered Jun 06 '26 00:06

Daniel Roseman


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.

like image 44
zom-pro Avatar answered Jun 06 '26 00:06

zom-pro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!