LoginSignup
0
1

More than 5 years have passed since last update.

n件ずつ順次キャッシュしながらイテレーションするサンプル

Posted at

「n件ずつキューを取得できる(消費したら消える)」というAPIがあるとき、イテレーションで1件ずつ処理するためのイテレーションクラス実装サンプル。

以下の例では取得した情報を内部でキャッシュしているので、アクセスせずに繰り返しイテレーションすることができる。(ただ、最後に追加のキューがないか調べようとしてしまう)

class StepCachingIterTest:
    def __init__(self, initial_list, cache_size):
        self.list = initial_list # 本当はアクセス先
        self.cache_size = cache_size
        self.cached_list = []
        self.idx = 0

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.cached_list) < self.idx + 1:
            loaded = self.load_cache(self.cache_size)
            if not loaded:
                self.idx = 0
                raise StopIteration()

        item = self.cached_list[self.idx]
        self.idx = self.idx + 1
        return item

    def load_cache(self, fetch_size):
        '''外部へのアクセス部分'''
        print('load_cache rest: ' + str(len(self.list)))
        if len(self.list) > 0:
            self.cached_list.extend(self.list[0:fetch_size])
            self.list = self.list[fetch_size:]
            return True
        else:
            return False

デバッグ用に print('load_cache rest: ' + str(len(self.list))) を入れてあるので、読み込みが実行されると表示される。

実際に実行するとこんな感じ。

> it = StepCachingIterTest(list(range(1,10)), 3)
> for i in it: 
..   print(i) 
..   
load_cache rest: 9
1
2
3
load_cache rest: 6
4
5
6
load_cache rest: 3
7
8
9
load_cache rest: 0
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1