Difference between revisions of "Python/ThreePartOperator"
From ProgrammingExamples
< Python
(add example of default assignment) |
(add final note) |
||
Line 12: | Line 12: | ||
example('yes',anum=99) # prints 'yes', default, 99, default | example('yes',anum=99) # prints 'yes', default, 99, default | ||
# etc | # etc | ||
− | </syntaxhighlight>. | + | </syntaxhighlight> |
+ | Note the use of the '''or''' operator. Python uses lazy left to right evaluation of that operator, so if the left operand is "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. |
Revision as of 14:33, 5 October 2011
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 is "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.