Main Content

Passing optional and named parameters to python methods

Archive - Originally posted on "The Horse's Mouth" - 2011-10-04 06:14:23 - Graham Ellis

When you call a named block of code (a method or function), you'll wish to pass in originating values that are changed from one call / use to the next - these are commonly known as the parameters. If I'm calling a function to calculate the area of a rectangle, for example, I would pass in the width and height, and if I'm calling a function to input a number from the keyboard I'm probably going to pass in the prompt message, and a minimum and maximum acceptable value.

There are some time, though, when you may want to leave out a parameter - let it be assumed. If I want to connect to a database, "localhost" would be a fair assumption if a host name is not given, for example.

In Python, I can specify optional parameters within the function definition by giving a name and assigning them to a default value, for example:
  def getload(lenny, seats, factor = 1.4):
will define a function that takes 2 or 3 parameters; if only 2 are specified, then the third one will take the assumed value of 1.4.

There are also times where you may wish to call your function with an indeterminate (and varying) number of parameters, and in this case you can add a * in front of the final named parameter and it will act as a sponge, gathering all remaining positional parameters into a list, for example:
  def average(first, *rest):
which is a function with at least one (but as many as you like) parameters. In practise, this isn't used all that often as it's far better to pass in a single list object from the calling code than to build a list of individual objects within the function in most circumstances.

Another possibility is that you may wish to call a function that could take a very large number of potentially different parameters, and they could be specified in any order. In Python, you can use named parameters by adding ** in front of the final parameter and you'll then be able to collect a dictionary of values. The function definition may look like:
  def bob(fred, cat="fullofbird", *rabbits, **kx):
with named parameters being collected in a dictionary called kx. Here's a sample call:
  bob(44,55,66,teeth=45,legs=3, arms=4)

Sample functions, and calls, shown above are in sample programs on our web site [here] and [here].




If you want to define the ultimate, generic function that will accept anything thrown at it, you can write your definition using the following structure:
  def wrapped(*args, **kwargs)

And if you want to call a function passing in such generics, you can do so in a similar way:
  finalanswer = why(*args, **kwargs)

Both of these example lines are taken from a recent example ([here]) I wrote to demonstrate decorators - wrappers that you can apply to functions or methods in Python for purposes such as logging calls and producing code coverage maps.