[TIP] replacing "break" with "continue" causes line to not be covered w/ coverage.py

Ned Batchelder ned at nedbatchelder.com
Sun Jul 3 06:42:46 PDT 2011


(Enormous hand-waving over significant details below)

If your code is this:

     10:    for item in container:
     11:        if item.some_condition() or item.some_other():
     12:            continue
     13:        item.do_real_stuff()

Then the generated code looks very crudely something like:

     10a:    start iterating container
     10b:    get next item
     11a:        if item.some_condition() jump to 12a
     11b:        if item.some_other() jump to 12a
     11c:        jump to 13a
     12a:        jump to 10b
     13a:        item.do_real_stuff()
     13b:        jump to 10b

The peephole optimizer sees that lines 11a and 11b include a jump to 
12a, but 12a is an unconditional jump to 10b, so it changes line 11a and 
11b:

     11a:        if item.some_condition() jump to 10b
     11b:        if item.some_other() jump to 10b

Line 12 is now never executed.

--Ned.


On 7/3/2011 9:09 AM, Eric Henry wrote:
> Right, but the point is that you're not doing anything else if the 
> condition is true.
>
> I can't say for sure, but it would seem that it could easily convert 
> the if ... continue into a "branch on equal" type bytecode. What 
> happens if you have a print statement before the continue?
>
> Eric
>
>
> On Sun, Jul 3, 2011 at 6:41 AM, Laurens Van Houtven <_ at lvh.cc> wrote:
>
>     Hang on. This appears to be for *unconditional* jumps. My jump
>     isn't unconditional, it's "if snr is None or prn is None:". How
>     does that get optimized away? Where's the always-true condition?
>     "prn is None or snr is None" is certainly not always true, in
>     fact, that's the exception, not the norm.
>
>     _______________________________________________
>     testing-in-python mailing list
>     testing-in-python at lists.idyll.org
>     <mailto:testing-in-python at lists.idyll.org>
>     http://lists.idyll.org/listinfo/testing-in-python
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20110703/7b7e4b6e/attachment.htm>


More information about the testing-in-python mailing list