『All You Need Is Kill』の実写映画版が2014年7月4日に日本全国で公開されることを記念して、Python で AllYouNeedIsKill
クラスを書いてみました。
aynik.py
# !/usr/bin/env python3
# vim:fileencoding=utf-8
# Copyright (c) 2014 Masami HIRATA <msmhrt@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__all__ = ['AllYouNeedIsKill']
class AllYouNeedIsKill:
def __init__(self, iterable):
self._iter_source = iter(iterable)
self._buffer = []
self._iter_buffer = None
def __iter__(self):
return self
def __next__(self):
if self._iter_buffer is not None:
try:
return next(self._iter_buffer)
except StopIteration:
self._iter_buffer = None
value = next(self._iter_source)
self._buffer.append(value)
return value
def rewind(self):
if self._buffer:
self._iter_buffer = iter(self._buffer)
else:
self._iter_buffer = None
def reset(self):
if self._iter_buffer is not None:
self._buffer = list(self._iter_buffer)
self.rewind()
else:
self._buffer = []
AllYouNeedIsKill
クラスのインスタンスは、引数のオブジェクトのイテレーターに巻き戻しのための rewind()
メソッドと、実行時点の状態を起点にするための reset()
メソッドを追加したイテレーターとして振る舞います。
サンプルは下記になります。
>>> from itertools import count # count() はひたすらカウントアップし続けるだけのイテレーター
>>> from aynik import AllYouNeedIsKill
>>> counter = AllYouNeedIsKill(count(1))
>>> next(counter)
1
>>> next(counter)
2
>>> counter.rewind() # 巻き戻しを実行する
>>> next(counter) # 巻き戻したので1になる
1
>>> next(counter)
2
>>> counter.reset() # 現在の状態を起点にする
>>> next(counter)
3
>>> counter.rewind() # 巻き戻しを実行する
>>> next(counter) # 返り値は1ではなく3になる
3
>>>
AllYouNeedIsKill
クラスは私の好みで無限長のイテレーターも扱えるようにしてありますが、関数ではなくクラスで実装していることと、標準ライブラリの itertools
の一部のツールのように入力されたイテレーターをタプルに展開はしないことが原因でパフォーマンスが低く、Pythonらしいコードにはなっていませんので、ご了承ください。
aynik.py
は二条項 BSD ライセンスで公開しますのでお好きにどうぞ。