Pass keyword arguments as required arguments in Python
I have, for example, 3 functions with the required arguments (some arguments are separated by 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 following dictionary:
argument_dict = {'a':3,'b':3,'c':23,'d':6,'e':1,'f':8}
Can functions be called this way ?:
value_one = function_one(**argument_dict)
value_two = function_two (**argument_dict)
value_three = function_three (**argument_dict)
source to share
I am assuming you are trying to create a function with undefined number of arguments. You can do this using args (arguments) or kwargs (keyword arguments like foo = 'bar'), for example, 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}
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 can do it that way and pad it with kwargs if you don't know what else the function might get.
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 on the level of abstraction of the object you are passing to the function. In your case, you pass the dictionary so you can handle this guy only.
source to share