Alternative suggestion for conditional expressions (see PEP 308)
Phil Frost
indigo at bitglue.com
Thu Jul 15 16:06:58 EDT 2004
On Thu, Jul 15, 2004 at 12:17:08PM -0700, Jeff Shannon wrote:
> Larry Bates wrote:
>
> >Seems that every one of the examples can be done
> >with a dictionary.
>
> While that may be true of the examples given here, it's not true of all
> cases. The one possible real advantage of a conditional expression, as
> I see it, is shortcutting. In cases where the conditionally-executed
> code has side effects, it can be important to ensure that *only* one
> branch is evaluated; creating an actual dictionary (whether permanent or
> temporary) will execute *all* branches. For example, using neblackcat's
> proposed syntax (even though I'm *not* fond of it):
>
> nextline = ?(FileOne.readline(), FileTwo.readline())[whichfile]
>
> ...
Evaluation of the expressions could be deferred by using callables, like
so:
next = (lambda: fileone.readline(), lambda filetwo.readline())[which]()
Or since in this example both sides of the tuple are already callables:
next = (fileone.readline, filetwo.readline)[which]()
But then really, is writing:
if which: next=fileone.readline()
else: next=filetwo.readline()
all that bad?
More information about the Python-list
mailing list