[Tutor] Use of "or" in a lambda expression
Steven D'Aprano
steve at pearwood.info
Sun Apr 5 05:11:33 CEST 2015
On Sat, Apr 04, 2015 at 02:21:19PM -0500, boB Stepp wrote:
> To my mind, would:
>
> def quit():
> print('Hello lambda world!')
> sys.exit()
>
> and:
>
> widget = Button(None, text='Hello event world!', command=quit)
>
> be preferable Python style?
Hell yes!
Using `or` to run functions purely for their side-effects (in this case,
printing and exiting) makes a nice trick, but I wouldn't use for real.
On the other hand, using `or` for its value is perfectly acceptable.
E.g. one common idiom might be to iterate over something which might be
None:
for value in maybe_list or []:
...
If `maybe_list` is a non-empty list, it is used; if it is an empty list,
the second operand (also an empty list) is used, but that's okay since
they are both empty lists; and if it is None, then the second operand is
used instead. This is a reasonable idiom to use, and prior to Python 2.5
it was the closest thing the language had to a "ternary if operator".
These days, the `or` idiom is less common except in old code or code
that has to run on Python 2.4 or older. Instead, we might write:
for value in (maybe_list if maybe_list is not None else []):
...
I'm not entirely sure that's an improvement :-)
--
Steve
More information about the Tutor
mailing list