Local variables persist in functions?

Scott David Daniels scott.daniels at acm.org
Sat Nov 25 21:03:37 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() ): ... 
> _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.
> 
> 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)

You've already got the real answer.  How about considering iterators,
since I presume you are chunking to help some kind of processing.:

     def chunky(src, size):
         '''Produce a (possibly long source) in size-chunks or less.'''
         assert size > 0
         for start in range(0, len(src), size):
             yield src[start : start + size]

     def chunkify(alist, size, _curList=None):
         if _curList is None:
             return list(chunky(alist, size))
         _curList.extend(list(chunky(alist, size)))
         return _curList

I suspect most often you can use chunky directly:
     for chunk in chunky(somedata, size):
         ...

     for size in range(1, 30):
         print size, list(chunky('abcdefghijklmnopqrstuvwxyz', size))


--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list