[Tutor] operator overloading considered harmful ;-)

spir denis.spir at free.fr
Sat Nov 7 19:01:29 CET 2009


Hello,

I jump on the opportunity offered by the previous thread to tell a little story (serious only people disgard). Guess this is a candidate for Bug of the Year.

I was filtering (parse) results to keep only nodes from a given set of types:

for child in node:
    if child.pattern in item_types:
        items.append(child)
    else:       # recursion
        ...

For a weird reason, _all_ child nodes were collected. So, I printed out node types at start of loop, but all was ok. After a while wondering, I printed patterns in the if branch, too -- which seemed to myself completely irrational:

for child in node:
    print child.pattern
    if child.pattern in item_types:
        print "*** type OK\t%s" %child.pattern
        items.append(child)
    else:       # recursion
        ...

This gave me results such as:
digit::[0..9] 
*** type OK     section::header body footer

The second expression is the one of another pattern in play during this test. Well, had a hard time finding out how the pattern, or its expression, could change between both prints. Actually, the reasons were (hope you're confortable):
* "section" is a recursive pattern (some items in the body can be sections)
* I had overloaded "==" in the top Pattern type as a syntactic sugar to name patterns.

Both together mean that, when the "in" test is performed, any child is (1) renamed and (2)returned (for the renaming to work), like a false result to the "==" comparison, so that the assertion always seems True.
[I have long considered this rule of python logic a flaw, but it's only me]
Actually, the logical relation is a bit obscured because, for me, patterns where compared for identity, not equality.

The funny joke here is that this trick for naming patterns is not necessary in normal use, only handy for testing. So that, probably, I'm the only one who could step on the bug.
For the little story, I did not find the solution, rather it fell into my head from who-knows-where while walking in the street on the way to market ;-)

Denis
------
la vita e estrany




More information about the Tutor mailing list