Fix Python – Normal arguments vs. keyword arguments

Question

Asked By – mk12

How are “keyword arguments” different from regular arguments? Can’t all arguments be passed as name=value instead of using positional syntax?

Now we will see solution for issue: Normal arguments vs. keyword arguments


Answer

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'}

This question is answered By – Ian Clelland

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0