Local variables persist in functions?

120psi at gmail.com 120psi at gmail.com
Fri Nov 24 09:11:09 CET 2006


I'm a bit baffled.  Here is a bit of fairly straightforward code:

def _chunkify( l, chunkSize, _curList = list() ):
    print _curList   # yay for printf debugging
    if len( l ) <= chunkSize:
        _curList.append( l )
    else:
        newChunk = l[:chunkSize]
        _curList.append( newChunk )
        _chunkify( l[chunkSize:], chunkSize, _curList )
    return _curList

_chunkify simply breaks a sequence into a sequence of smaller lists of
size <= chunkSize.  The first call works fine, but if I call it
multiple times, weirdness happens.

chunks = _chunkify( list, size )   # _curList keeps its previous value!
chunks = _chunkify( list, size, list() )    # this works as expected

Considering the default value of _curList, these statements should be
identical.  Any pointers?  Did I miss something in the python reference
manual?  (running 2.4.3, fyi)

Thanks,
Nils




More information about the Python-list mailing list