PageRenderTime 5ms CodeModel.GetById 1ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/indra/lib/python/indra/util/iterators.py

https://bitbucket.org/lindenlab/viewer-beta/
Python | 63 lines | 54 code | 0 blank | 9 comment | 0 complexity | 6222c62913f11e5a1d3590b313f168f8 MD5 | raw file
 1"""\
 2@file iterators.py
 3@brief Useful general-purpose iterators.
 4
 5$LicenseInfo:firstyear=2008&license=mit$
 6
 7Copyright (c) 2008-2009, Linden Research, Inc.
 8
 9Permission is hereby granted, free of charge, to any person obtaining a copy
10of this software and associated documentation files (the "Software"), to deal
11in the Software without restriction, including without limitation the rights
12to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13copies of the Software, and to permit persons to whom the Software is
14furnished to do so, subject to the following conditions:
15
16The above copyright notice and this permission notice shall be included in
17all copies or substantial portions of the Software.
18
19THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25THE SOFTWARE.
26$/LicenseInfo$
27"""
28
29from __future__ import nested_scopes
30
31def iter_chunks(rows, aggregate_size=100):
32    """
33    Given an iterable set of items (@p rows), produces lists of up to @p
34    aggregate_size items at a time, for example:
35    
36    iter_chunks([1,2,3,4,5,6,7,8,9,10], 3)
37
38    Values for @p aggregate_size < 1 will raise ValueError.
39
40    Will return a generator that produces, in the following order:
41    - [1, 2, 3]
42    - [4, 5, 6]
43    - [7, 8, 9]
44    - [10]
45    """
46    if aggregate_size < 1:
47        raise ValueError()
48
49    def iter_chunks_inner():
50        row_iter = iter(rows)
51        done = False
52        agg = []
53        while not done:
54            try:
55                row = row_iter.next()
56                agg.append(row)
57            except StopIteration:
58                done = True
59            if agg and (len(agg) >= aggregate_size or done):
60                yield agg
61                agg = []
62    
63    return iter_chunks_inner()