try: and while/continue don't mix? Bizarre behavior with function calls.

Bill McKinnon bill_mckinnon at interloper.net
Tue Dec 4 22:44:03 EST 2001


Ok, this one had me swearing I was going insane for a few minutes. I
whittled a 500 line snippet of code that was acting strangely down to
this example:

--
import sys, re

def func(lines):
    print "func() called."
    dataRe = re.compile(r'(\d+)')
    inserted = {}
    while 1:
        print "  Entering while loop."
        if len(lines) == 0:
            break
        line = lines[0]
        lines = lines[1:]
        match = dataRe.search(line)
        if not match:
            continue
        str = match.groups()
        try:
            if inserted.has_key(str):
                continue
            inserted[str] = 1
        except "invalidValue":
            pass
        print "  Exiting while loop."
    print "Exiting function."


# mainline
lines = ["11111", "11111"]    
func(lines)
--

   Can anyone explain to me how getting this for output is not a bug
in Python? The function is getting called twice:

--
func() called.
  Entering while loop.
  Exiting while loop.
  Entering while loop.
  Entering while loop.
func() called.
  Entering while loop.
Exiting function.
--

   This is happening with "ActivePython 2.1, build 210 ActiveState"
and with Python 2.1 under Linux that I built myself. Things that are
interesting to note:

- Making the lines list contain an odd number of identical values
makes the   problem go away.

- Commenting out either the if inserted.has_key(str): / continue lines
OR the   assignment to inserted[str] line makes the problem go away.

- Removing the try: block makes the problem go away.

- Removing the regex stuff makes the problem go away.

   I'm guessing that jumping in and out of the try: block with the
continue call is fouling something up. I'd be delighted to find out
that I'm doing something wrong and that it's not a python interpreter
level thing. Can anyone shed any light on this one? Thanks...

- Bill



More information about the Python-list mailing list