Main Content

Optional and named parameters in Python

Archive - Originally posted on "The Horse's Mouth" - 2008-11-05 03:44:47 - Graham Ellis

When you're calling a named block of code (either a function or a method in Python terms), you'll pass in a number of parameters. Some of those will be mandatory - needed every time. Some will be optional, but frequently used, and others will be wanted on very rare occasions indeed and selected from a potentially huge number of possibilities.

Calls to a Python function (and the matching declaration) normally start with the mandatory parameters, followed by the optional but most-often-wanted ones, and finally the less common ones.

• There are some straightforward functions defined and called in this example (opens in new window, as do all following source links)

• There are some fucntion calls making use of optional parameters, and calling functions in a separately loaded file here and the function file is here.

• There's an example of "call by name" where the caller tells the function which parameter is which, and also an example of a call that puts a whole load of values into a single list (like sponging up remaining paramaters) here

And finally - a new example from yesterday which I'll explain in a bit more detail - main source code here and the module in calls here. What does it show?

1. You can bring in another file of functions into your current namespace using the from statement. You can bring those function in to a namespace that's the same as the file name from which they are loaded by using the import statement. And (new demo) you can use import as to bring them in from a file but to a different namespace. Example:
  import taxcalcs as tc

Why would you want to do this? Because you might have some long file names and paths that you don't want to have to keep stating, or you might have two alternative modules and wish to change the code simply by changing a single import statement.

2. If you add a parameter with two asterixes (**) on the end of a function definition, that parameter is taken as being the name of a dictionary into which all otherwise unidentified parameters are stored.

Why would you want to do this? to give a huge flexibility to the call - being able to pass in anything you wished without the need for each item passed in to set up its own variable. It's much more secure as a function writer to palce all your user's named additions into a single dictionary than to allow them to spill all over your namespace.

Example call:
net = tc.getnet(amount,country="Slovenia",taxrate=20,
  year=2008,type="VAT")


Example function:
def getnet(gross, taxrate=17.5, **others):
  net = gross / (1.0 + taxrate*0.01)
  for more in others.keys():
    print "GETNET:",more," - ",others[more]
  return neto


Part of the sample output:
How much did you spend? 120.00
GETNET: country - Slovenia
GETNET: type - VAT
GETNET: year - 2008
That was 100.0 for the merchant (Slovenia)