Bizarre behavior with mutable default arguments

Istvan Albert istvan.albert at gmail.com
Sun Dec 30 15:54:25 EST 2007


On Dec 30, 3:41 pm, bukzor <workithar... at gmail.com> wrote:

> No globals, as you specified. BTW, it's silly not to 'allow' globals
> when they're called for, otherwise we wouldn't need the 'global'
> keyword.

okay, now note that you do not actually use the ingroup list for
anything else but getting and setting its first element. So why would
one really need it be a list? Let's replace it with a variable called
ingroup that is not a list anymore. See it below (run it to see what
happens):

----------------------

def blocks(s, start, end):
    ingroup = 0
    def classify(c):
        klass = c==start and 2 or c==end and 3 or ingroup
        ingroup = klass==1 or klass==2
        return klass
    return [tuple(g) for k, g in groupby(s, classify) if k == 1]

print blocks('the {quick} brown {fox} jumped', start='{', end='}')







More information about the Python-list mailing list