Local variables persist in functions?
robert
no-spam at no-spam-no-spam.invalid
Fri Nov 24 04:37:51 EST 2006
120psi at gmail.com wrote:
> 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)
>
the default list() is only created once when the function is defined. And its later its always the same list
Use
def _chunkify( l, chunkSize, _curList=None ):
_curList = _curList or []
...
then it works.
Robert
More information about the Python-list
mailing list