Main Content

Optional parameters to Python functions

Archive - Originally posted on "The Horse's Mouth" - 2009-10-07 21:38:48 - Graham Ellis

Python functions (and methods) can be called with any number (0 or more) parameters, but the calling sequence must match the 'template' or 'function prototype' given when defining the function. Let's define a function:

def fred(a,b,c=3,d=4,e=5,f=6):
    print a,b,c,d,e,f


That function can be called with a minimum of two parameters, and a maximum of six. The mandatory ones are filled into variables called "a" and "b" and any others into "c", "d", "e" and "f". If there aren't enough values, then "f" will become 6, "e" will become 5, "d" will become 4 and "c" will become 3. In other words, values fill in from the beginning.

If you want to fill in some of the optional values, but not from the 'left', you can do so by specifying the name of the variable within the function and its value:

fred (1,2,10,20)
fred (1,2,10,e=20)
fred (1,2,10,f="shishcake",e=20)


Running that:

Dorothy-2:3 grahamellis$ python dxz2
1 2 10 20 5 6
1 2 10 4 20 6
1 2 10 4 20 shishcake
Dorothy-2:3 grahamellis$