Normal arguments vs. keyword arguments Normal arguments vs. keyword arguments python python

Normal arguments vs. 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.


Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:

def foo(bar, baz):    passfoo(1, 2)foo(baz=2, bar=1)


matomo