Style question for conditional execution

Arnaud Delobelle arnodel at gmail.com
Wed Nov 24 15:25:19 EST 2010


Gerald Britton <gerald.britton at gmail.com> writes:

> Writing in Python gives me the luxury of choosing different paradigms
> for similar operations.  Lately I've been thinking about a minor
> detail that peaked my interest and am curious what others think:
>
> Say that I have some function "f" that I will execute if some variable
> "v" evaluates true.  Using a classical procedural approach, I might
> write:
>
>     if v:
>         f()
>
> I might, however, think more in a functional-programming direction.
> Then I might write:
>
>     v and f()
>
> Interestingly, this second expression compiles smaller (though only by
> a little) in both Python 2.6 and 3.1, which I currently have
> installed.  If I had thousands of such expressions, I could boast
> about a measurable difference but practically speaking, it is not
> significant.
>
> What I _am_ interested in, however, is feedback from a style perspective.
>
> What do the rest of you think about this?
>
> Have you used the second approach and, if so, what was your motivation?
>
> Is there a good/bad reason to choose one over the other?

I would use the if: form every time but it's interesting that the
"JUMP_FORWARD 0" instruction below doesn't get optimised away.

If it did, both forms would be the same compiled lengths.

>>> def g():
...     if v: f()
... 
>>> dis.dis(g2)
  2           0 LOAD_GLOBAL              0 (v) 
              3 POP_JUMP_IF_FALSE       16 
              6 LOAD_GLOBAL              1 (f) 
              9 CALL_FUNCTION            0 
             12 POP_TOP              
             13 JUMP_FORWARD             0 (to 16) 
        >>   16 LOAD_CONST               0 (None) 
             19 RETURN_VALUE         

-- 
Arnaud



More information about the Python-list mailing list