1.

What is the advantage of employing keyword arguments in definition of function? How can we force compulsory usage of keyword arguments in function call?

Answer»

Function is a reusable block of statements. WHENEVER called, it performs a certain PROCESS on parameters or arguments if passed to it. Following function receives two integers and returns their division

>>> def division(x,y): return x/y >>> division(10,2) 5.0

While calling the function, arguments must be passed in the same sequence in which they have been defined. Such arguments are called positional arguments. If it is desired to provide arguments in any other order, you must use keyword arguments as follows:

>>> def division(x,y): return x/y >>> division(y=2, x=10) 5.0

The formal names of arguments are used as keywords while calling the function. However, using keyword arguments is optional. Question is how to define a function that can be called only by using keywords arguments?

To force compulsory use of keyword arguments, use '*' as one parameter in parameter list. All parameters after * become keyword only parameters. Any parameters before * continue to be positional parameters.

>>> def division(*,x,y): return x/y >>> division(10,2) Traceback (most recent call last):  FILE "<pyshell#7>", line 1, in <module>    division(10,2) TypeError: division() takes 0 positional arguments but 2 were given >>> division(y=2, x=10) 5.0 >>> division(x=10, y=2) 5.0

In above example, both arguments are keyword arguments. Hence keyword arguments must be used even if you intend to pass values to arguments in the same order in which they have been defined.

A function can have MIX of positional and keyword arguments. In such case, positional arguments must be defined before ‘*’

In following example, the function has two positional and two keyword arguments. Positional arguments may be passed using keywords also. However, positional arguments must be passed before keyword arguments.

>>> def sumdivide(a,b,*,c,d): return (a+b)/(c-d) >>> sumdivide(10,20,c=10, d=5) 6.0 >>> sumdivide(c=10, d=5,a=10,b=20) 6.0 >>> sumdivide(c=10, d=5,10,20) SyntaxError: positional argument follows keyword argument


Discussion

No Comment Found