GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — unpythonic/unpythonic/gtco.py at master · Technologicat/unpythonic Expand file tree/ Copy pathgtco.pyMore file actions 68 lines (56 loc) · 2.23 KB / Copy pathgtco.pyFile metadata and controls68 lines (56 loc) · 2.23 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 # -*- coding: utf-8 -*- """Tail call optimization for generators.""" __all__ = ["gtco", "gtrampolined"] from collections.abc import Callable, Generator from functools import wraps from inspect import isgenerator from typing import Any, TypeVar F = TypeVar('F', bound=Callable) def gtco(generator: Generator) -> Generator: """Low-level function: run a generator with TCO enabled. In the generator, use ``return`` to tail-chain to the next generator. Example:: def march(): yield 1 yield 2 return march() # tail-chain to a new instance of itself assert tuple(take(6, gtco(march()))) == (1, 2, 1, 2, 1, 2) last(take(10000, gtco(march()))) # no crash """ while True: # trampoline x = yield from generator # yield stuff, get final result (return ...) # don't let the TCO jump target bring along its trampoline if it has one if isinstance(x, _TrampolinedGenerator): x = x.g if isgenerator(x): generator = x else: # usually the return value is None, but allow for an iterable try: yield from x # the last batch! except TypeError: return x # passthrough def gtrampolined(gfunc: F) -> F: """Decorator for generator functions (i.e. definitions of generators). Decorating the definition avoids the need to use ``gtco`` at call time. Example:: @gtrampolined def ones(): yield 1 return ones() assert tuple(take(10, ones())) == (1,) * 10 last(take(10000, ones())) # no crash """ @wraps(gfunc) def trampolining_gfunc(*args: Any, **kwargs: Any) -> "_TrampolinedGenerator": generator = gfunc(*args, **kwargs) return _TrampolinedGenerator(generator) # inject a trampoline return trampolining_gfunc class _TrampolinedGenerator: """Wrapper to inject the gtco() call to the generator g returned by gfunc.""" def __init__(self, g: Generator) -> None: self.g = g def __iter__(self) -> Generator: return gtco(iter(self.g)) # start the trampoline # no __next__, because __iter__ redirects; # this wrapper is never actually iterated over. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |