-2

I hava a question about *args and **kwargs. I know that they are used when you do not know how many arguments will be passed to function. But can it be a substitute for some arguments that are actually required when I do not know what those are?

If there is a function:

def functionName(a, b):
    ...some code...
    doSomethingUsing(a)
    doSomethingUsing(b)

If I do not what arguments does the function take can I simply use functionName(*args, **kwargs) - or functionName(*args)? I noticed that some people tend to use it that way - but I am not sure if this is how * and ** work in python?

McCzajnik
  • 163
  • 1
  • 12
  • The calls `functionName(*args)` are *unpacking* whatever `args` is into `functionName`. – juanpa.arrivillaga Jul 03 '17 at 04:34
  • You can look at Peter Hoffmann's answer https://stackoverflow.com/a/36908/6683117 – Logovskii Dmitrii Jul 03 '17 at 04:44
  • This question is not clear and probably a duplicate. It sounds like you just want to throw arbitrary arguments at a function and it should magically know what it needs. You always have to know what arguments a function takes, how else can you be sure that you're using it correctly? Please clarify what you want to achieve. – skrx Jul 03 '17 at 05:24
  • Well, I suspected I am going to get downvoted for that - but it was worth it - thanks for the answers and links it is much clearer now. – McCzajnik Jul 03 '17 at 05:33

2 Answers2

1

Calling function(*args) is equivalent to function(arg[0], arg[1],...,arg[N]).

If you don't know what arguments the function is expecting, just call it and look at the exception:

>>> def f(a,b,c):
...     pass
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() missing 3 required positional arguments: 'a', 'b', and 'c'

Or you could use the interactive help.

>>> help(f)
Help on function f in module __main__:

f(a, b, c)
import random
  • 3,054
  • 1
  • 17
  • 22
0

yes you can use the *args and **kwargs at the same time but the orders matters you can have the idea here. if you want to use all two of these in functions then the order is

some_func(*args,**kwargs)
jarry jafery
  • 1,018
  • 1
  • 14
  • 25