Is it true that in a python function with keyword parameters only in the definition, that it is legal to call the function with no arguments ? And are there other exceptions to rule that there must be arguments in a function call when there are parameters in the definition ?
If you give the parameter a default value, then it becomes optional.
For example:
def aFunction(foo, bar=None):
if bar is not None:
print(foo, bar)
else:
print(foo)
That function can be called this way: aFunction(fooVar)
Or this way: aFunction(fooVar, barVar)
There are other situations where you may see “arguments” in a function definition, but the function may be called without arguments. E.g. *args
in the definition would capture any positional arguments as a tuple, which may be empty if no arguments were passed:
>>> def foo(*args):
... print(args)
...
>>> foo(1, 2, 1.618)
(1, 2, 1.618)
>>> foo()
()
Similarly **kwargs
will capture named/keyword arguments as a dictionary, and no named arguments would result in an empty dictionary:
>>> def bar(**kwargs):
... print(kwargs)
...
>>> bar(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
>>> bar(a=1, b=2)
{'a': 1, 'b': 2}
>>> bar()
{}
Sometimes you may see a function definition like def foo(*args, **kwargs)
, which takes any kind and number of arguments, for whatever reasons it needs to be that flexible.
2 Likes