Python: Functions with Optional & Named Arguments

Python allows functions to have default values for arguments. These are used when the function is called without the argument. But where it gets really interesting is when you realize that in Python it’s also possible to name the arguments and call them in any order, which can be very useful.

def shirt(styleID, size='Medium', color='White'):
...

For example, in the ‘shirt’ function above, style is a required argument (since it has no default value) but the other two arguments i.e. size and color are optional (since they do have default values assigned).

There are several ways to call this function:

shirt(1)

styleID gets a value of 1 and size and color are assigned their default values.

shirt(1, "Large")

styleID gets a value of 1 and size gets a value of “Large”, while color gets the default value.

shirt(1, color="Black")

styleID gets a value of 1 and color gets a value of “Black”, while size gets the default value.

shirt(size="Small", styleID=2)

size gets a value of “Small” and styleID gets a value of 2, while color gets the default value.