Python/ThreePartOperator

From ProgrammingExamples
< Python
Revision as of 14:34, 5 October 2011 by Griswolf (Talk | contribs)

Jump to: navigation, search

Python does not supply the ?: operator, but it is sometimes very nice. Here's how to mimic it

We often want to set local variables to "what was passed, or if not, a default" like this:

def example(required, alist=None, anum=None, astring=''):
  my_list = alist or ['item']
  my_num = anum or 666
  my_string = astring or 'string'
  print('required: "%s"\nlist: %s\nNumber: %s\nString: "%s"'%(required, my_list,my_num,my_string))
 
example('must') # prints 'must' plus the three defaults
example('yes',anum=99) # prints 'yes', default, 99, default
# etc

Note the use of the or operator. Python uses lazy left to right evaluation of that operator, so if the left operand evaluates as True the assignment takes it, else it takes the right operand.

There are some issues (what if you want the default to be something that evaluates as False?) but this technique will work often enough to be worth knowing.