Easy function, please help.

Terry Reedy tjreedy at udel.edu
Thu Feb 10 18:01:57 CET 2011


On 2/10/2011 11:52 AM, Ethan Furman wrote:
> Jason Swails wrote:


>> How is "while n != 0:" any worse?

1. It is redundant, just like 'if bool_value is not False:'.
Python programmers should understand the null value idiom.

2. It does 2 comparisons, 1 unneeded, instead of 1. For CPython,
it adds 2 unnecessary bytecode instructions and takes longer.

 >>> from dis import dis
 >>> def f(n):
	while n: pass

	
 >>> dis(f)
   2           0 SETUP_LOOP              10 (to 13)
         >>    3 LOAD_FAST                0 (n)
               6 POP_JUMP_IF_FALSE       12
               9 JUMP_ABSOLUTE            3
         >>   12 POP_BLOCK
         >>   13 LOAD_CONST               0 (None)
              16 RETURN_VALUE
 >>> def f(n):
	while n != 0: pass

	
 >>> dis(f)
   2           0 SETUP_LOOP              16 (to 19)
         >>    3 LOAD_FAST                0 (n)
               6 LOAD_CONST               1 (0)
               9 COMPARE_OP               3 (!=)
              12 POP_JUMP_IF_FALSE       18
              15 JUMP_ABSOLUTE            3
         >>   18 POP_BLOCK
         >>   19 LOAD_CONST               0 (None)
              22 RETURN_VALUE


>> It has exactly the same effect without adding any code

Untrue, see above.



-- 
Terry Jan Reedy




More information about the Python-list mailing list