Main Content

Optional positional and named parameters in Python

Archive - Originally posted on "The Horse's Mouth" - 2012-11-23 02:06:34 - Graham Ellis

Functions are commonly called with a set number of positional parameters. However, you have more flexibility in Python.

If you define your function with a parameter starting with a "*", then all remaining parameters after anything to its left are stored in that parameter as a tuple. And if you conclude your parameter list with a parameter starting "**", then you can pass in key, value pairs which will be stored into that named parameter as a dict.

For example:
  def summat(ilm, *others, **occasionals):
defines a function into which the first calling parameter is put into "ilm", other positional parameters (if any) into "others" and anything that'a named into "occasionals. So if I call this as follows:
  summat(4.5, 2, "Zaphod", protocol = "Matian", system = "Solar")
I'll get
  ilm 4.5
  others (2, 'Zaphod')
  occasionals {'protocol': 'Matian', 'system': 'Solar'}


The same * and ** notation can be used in the call to a function too - there's an example from the Intermediate Python course that finished today [here] on our web site.