From 77dd732a3b3b604a6029e748ffd4fb0b9760642d Mon Sep 17 00:00:00 2001 From: Fredrik Tolf Date: Sat, 2 Feb 2013 06:25:37 +0100 Subject: [PATCH] Moved the iterproxy to an optionally usable preiter in wrw.util. --- wrw/dispatch.py | 28 +--------------------------- wrw/util.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 27 deletions(-) diff --git a/wrw/dispatch.py b/wrw/dispatch.py index fa1f669..4d22b72 100644 --- a/wrw/dispatch.py +++ b/wrw/dispatch.py @@ -16,32 +16,6 @@ def mangle(result): return result return [str(result)] -class iterproxy(object): - # Makes sure iter(real).next() is called immediately, in order to - # let generator code run. - def __init__(self, real): - self.bk = real - self.bki = iter(real) - self._next = [None] - self.next() - - def __iter__(self): - return self - - def next(self): - if self._next is None: - raise StopIteration() - ret = self._next[0] - try: - self._next[:] = [self.bki.next()] - except StopIteration: - self._next = None - return ret - - def close(self): - if hasattr(self.bk, "close"): - self.bk.close() - def defaulterror(req, excinfo): import resp traceback.print_exception(*excinfo) @@ -60,7 +34,7 @@ def handle(req, startreq, handler): resp = [""] while True: try: - resp = iterproxy(handler(req)) + resp = handler(req) break except restart, i: handler = i.handle diff --git a/wrw/util.py b/wrw/util.py index 6368b18..55b4ee2 100644 --- a/wrw/util.py +++ b/wrw/util.py @@ -34,6 +34,37 @@ def persession(data = None): return wrapper return dec +class preiter(object): + __slots__ = ["bk", "bki", "_next"] + end = object() + def __init__(self, real): + self.bk = real + self.bki = iter(real) + self._next = None + self.next() + + def __iter__(self): + return self + + def next(self): + if self._next is self.end: + raise StopIteration() + ret = self._next + try: + self._next = next(self.bki) + except StopIteration: + self._next = self.end + return ret + + def close(self): + if hasattr(self.bk, "close"): + self.bk.close() + +def pregen(callable): + def wrapper(*args, **kwargs): + return preiter(callable(*args, **kwargs)) + return wrapper + class sessiondata(object): @classmethod def get(cls, req, create = True): -- 2.11.0