For any function in Python, we can have two types of arbitrary arguments:
Positional arguments: These are function arguments that need to be fed to the function in the specific order as they were defined.
Keyword argument: These are function arguments that have been given a name/keyword during the function definition. You need to identify the specific keyword when passing a keyword argument (kwarg) to a function.
Keyword arguments can be fed in any order, but need to be specified with their keyword in the following manner:
The syntax example above shows how you can pass multiple keyword arguments in a function requiring them. You need to specify the name of the keyword argument followed by a =
and then by the parameter you want to pass. If the function accepts multiple kwargs, then you can specify your parameters in any order. The function automatically matches the keyword to the correct function variables.
Functions with kwargs can even take in a whole dictionary as a parameter; of course, in that case, the keys of the dictionary must be the same as the keywords defined in the function.
You cannot directly send a dictionary as a parameter to a function accepting kwargs. The dictionary must be unpacked so that the function may make use of its elements. This is done by unpacking the dictionary, by placing
**
before the dictionary name as you pass it into the function.
The following is a program showing how you can use a dictionary instead of inputting each kwarg.
def myfunc(name, gender, age):print (name," is a ", gender, " of age ", age)mydict = {'name': "Faraz", 'gender': "male", 'age': "20"}myfunc(**mydict)
Sometimes, we need to have a variable number of kwargs in a function; in such cases, the function packs all the arguments in a single dictionary.
The following is the definition of such a function:
Functions with similar definitions can take in an arbitrary number of kwargs and can take in a dictionary of arbitrary length. In this case (differing from the previous), the dictionary keys do not need to be anything specific. This could be considered similar to sending a list to a function.
The following example helps us understand how such a function would unpack and use a dictionary:
def myfunc(**kwargs):print("I work with the follwoing people: ")for people in kwargs:print (kwargs[people])mydict = {'person1': "Faraz", 'person2': "Rukhshan", 'person3': "Muzammil"}myfunc(**mydict)
Free Resources