Local variables persist in functions?
John Machin
sjmachin at lexicon.net
Fri Nov 24 03:54:35 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() ):
Quite apart from the default argument problem, which Duncan has
addressed, you have some problems with style and variable names. In
particular: give variables meaningful names ; "L".lower() is not
meaningful and also suffers from confusion with the digit 1 in some
fonts. There is no necessity for the _ in _curList in the above line.
Please consider reading http://www.python.org/dev/peps/pep-0008/
> 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
Is the first "list" a list, or is it the name of the same function that
you are calling to provide the 3rd argument?
[snip]
HTH,
John
More information about the Python-list
mailing list