-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?

4
  • The calls functionName(*args) are unpacking whatever args is into functionName. Jul 3, 2017 at 4:34
  • You can look at Peter Hoffmann's answer stackoverflow.com/a/36908/6683117 Jul 3, 2017 at 4: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 3, 2017 at 5: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 3, 2017 at 5:33

2 Answers 2

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)
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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.