How are "keyword arguments" different from regular arguments? Can't all arguments be passed as name=value
instead of using positional syntax?
There are two types of arguments in a function which are positional arguments (declared by a name only) and keyword arguments (declared by a name and a default value). When a function is called, values for positional arguments must be given.
Keyword arguments can often be used to make function calls more explicit. This takes a file object output_file and contents string and writes a gzipped version of the string to the output file. Notice that using this keyword argument call style made it more obvious what each of these three arguments represent.
Keyword arguments are called with user-defined keywords that can be specified in any order. In the macro body, the argument name is preceded by an exclamation point. On the macro call, the argument is specified without the exclamation point.
5 Types of Arguments in Python Function Definition:positional arguments. arbitrary positional arguments. arbitrary keyword arguments.
There are two related concepts, both called "keyword arguments".
On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.
The other concept is on the function definition side: you can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is
def my_function(arg1, arg2, **kwargs)
Any keyword arguments you pass into this function will be placed into a dictionary named kwargs
. You can examine the keys of this dictionary at run-time, like this:
def my_function(**kwargs): print str(kwargs) my_function(a=12, b="abc") {'a': 12, 'b': 'abc'}
There is one last language feature where the distinction is important. Consider the following function:
def foo(*positional, **keywords): print "Positional:", positional print "Keywords:", keywords
The *positional
argument will store all of the positional arguments passed to foo()
, with no limit to how many you can provide.
>>> foo('one', 'two', 'three') Positional: ('one', 'two', 'three') Keywords: {}
The **keywords
argument will store any keyword arguments:
>>> foo(a='one', b='two', c='three') Positional: () Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}
And of course, you can use both at the same time:
>>> foo('one','two',c='three',d='four') Positional: ('one', 'two') Keywords: {'c': 'three', 'd': 'four'}
These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With