Python - Passing argument by argument name

Introduction

In Python you can pass argument by name, instead of by position.

Demo

def f(a, b, c): print(a, b, c) 
print( f(c=3, b=2, a=1) )

Result

The c=3 in this call, means send 3 to the argument named c.

Python matches the name c in the call to the argument named c in the function definition's header.

It's possible to combine positional and keyword arguments in a single call.

In this case, all positionals are matched first from left to right in the header, before keywords are matched by name:

Demo

def f(a, b, c): print(a, b, c) 

f(1, c=3, b=2)            # a gets 1 by position, b and c passed by name
# from   w w  w .j a  va2s  . c  om

Result

Keywords make your calls a bit more self-documenting.

For example, a call of this form:

func(name='Bob', age=40, job='dev') 

Related Topic