[Python-ideas] if expensive_computation() as x:

Nick Coghlan ncoghlan at gmail.com
Sat Feb 15 02:12:38 CET 2014


On 15 February 2014 10:49, Chris Angelico <rosuav at gmail.com> wrote:
> And that's my point. No matter how the *computer* sees them, the
> *programmer* sees them as peers. Adding an additional option to the
> list should not change the indentation level of any other, because the
> logical structure of the code hasn't changed.

You snipped the salient point in all this: the relevant case is one
where the programmer wants to check *different* things, and *only*
wants to calculate them if the earlier things are false. If they were
true peers, this approach would work:

    x = alternative_1()
    y = alternative_2()
    z = alternative_3()

    if x:
        # Do something with x
    elif y:
        # Do something with y
    elif z:
        # Do something with z

Ram's concern is that the calculation of y and z isn't needed if x is
true, and these calculations are considered to expensive to execute
unconditionally, so calculating all three up front isn't wanted. The
natural shortcircuiting translation of that is nested if statements,
not an elif chain, because these *aren't* peers, the programmer
actually wants execution of the later calculations to be conditional
on the results of the earlier ones:

    x = alternative_1()
    if x:
        # Do something with x
    else:
        y = alternative_2()
        if y:
            # Do something with y
        else:
            z = alternative_3()
            if z:
                # Do something with z

If the response to this recommendation is "but I need them all to be
bound to x, because x gets reused later in the function and these are
just different ways of calculating x", then we have *definitely*
reached the point where the correct answer is not "make this kind of
spaghetti code easier to write", but instead "refactor the function so
that calculating x is a clearly distinct named operation":

    x = calculate_x()

And if the objection to *that* is "but I don't like factoring out
functions that are only used once", then the appropriate response is
to keep looking for a better way to handle one-shot function
definitions (along the lines of PEPs 403 and 3150), not attempting to
reduce the number of cases where factoring out a one shot function is
appropriate by encouraging more spaghetti code.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list