3

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)
1
  • Yes I have tried and I have TypeError as Daniel says Commented Apr 19, 2015 at 16:12

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Daniel, so the pythonic way of write funcions is this (e.g.): def function_two(b,c,e, **kwargs): ... def function_three(f,a,c,d, **kwargs): ... Or this??: def function_two(**kwargs): ... def function_three(**kwargs): ...
the key there is to understand what do you know you will be giving to the function. Let's say I know will give the function a and b and then a bunch of other arguments, you can use def f(a, b, *args) then if I also will use keyword arguments, def f(a, b, *args, **kwargs). (Kwargs are of the type c=1, d=2)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.