Decorator-based implementation of PEP 380 (yield from). This is the optimized version (special handling of nested "yield _from"s).
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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | from compat.functools import wraps as _wraps
from sys import exc_info as _exc_info
from weakref import WeakValueDictionary as _WeakValueDictionary
# use WeakValueDictionary to associate data with generator instances
# for alternative, wrapper-based solutions, see
# <http://code.activestate.com/recipes/164044/>
_yieldingfrom = _WeakValueDictionary()
class _shared_stack(object):
"""Stack whose top parts can also be stacks.
Sample usage:
>>> m = _shared_stack(); m.push("m", [])
>>> n = _shared_stack(m); m.push("n", []) # initialize n from m's head
>>> # m and n now have same head
>>> o = _shared_stack(n); n.push("o", []) # pushes to both
>>> p = _shared_stack(n)
>>> q = _shared_stack(); n.push("p", q.root())
>>> m._trace()
[] # q's root, head of m,n,o,p,q
['p', []] # p's root, top of m,n,o,p
['o', ['p', []]]
['n', ['o', ['p', []]]] # n's root
['m', ['n', ['o', ['p', []]]]] # m's root
>>> m._headstack()[0] is q.root()
True
"""
def __init__(self, data=None):
"""Initializing with another shared_stack
makes a stack with the same head."""
if data is None:
data = []
elif isinstance(data, _shared_stack):
data, _ = data._headstack()
# Implemented as a dict:
# {'head': head_list, list_id: previous_list, ...
# 'root': root_list, root_list_id: True}
self._stack = {'head': data, 'root': data, id(data): True}
def _headstack(self):
stack = self._stack
head = stack['head']
while True:
# pop levels until previous_list is not empty
head_id = id(head)
if stack[head_id]:
# root_list_id also points to a True value
break
stack['head'] = head = stack.pop(head_id)
while head:
# expand until previous_list's final element is empty
stack['head'] = next = head[-1]
stack[id(next)] = head
head = next
return head, stack
def root(self):
return self._stack['root']
def top(self):
head, stack = self._headstack()
top = stack[id(head)]
return (top if top is not True else None)
def push(self, *args):
head, _ = self._headstack()
head.extend(args)
def pop(self):
head, stack = self._headstack()
if head is stack['root']:
raise IndexError("pop from empty stack")
stack['head'] = prev = stack.pop(id(head))
del prev[:]
def __nonzero__(self):
head, stack = self._headstack()
return head is not stack['root']
def _trace(self):
head, stack = self._headstack()
print "Tracing 0x%x:" % (id(self),)
while True:
print '0x%x=%s' % (id(head), head)
head = stack[id(head)]
if head is True: break
def __repr__(self):
return '_shared_stack(%r)' % (self._shared_stack['root'],)
class _from(object):
def __init__(self, EXPR):
self.iterator = iter(EXPR)
def supergenerator(genfunct):
"""Implements PEP 380. Use as:
@supergenerator
def genfunct(*args):
try:
sent1 = (yield val1)
...
retval = yield _from(iterator)
...
except Exception, e:
# caller did generator.throw
pass
finally:
# closing
pass
"""
@_wraps(genfunct)
def wrapper(*args, **kwargs):
gen = genfunct(*args, **kwargs)
_yieldingfrom[gen] = gen_yf = _stack()
try:
# if first poll of gen raises StopIteration
# or any other Exception, we propagate
item = gen.next()
# OUTER loop
while True:
# yield _from(EXPR)
# semantics based on PEP 380, Revised**12, 19 April
if isinstance(item, _from):
_i, _iyf = item.iterator, None
try:
# first poll of the subiterator
_y = _i.next()
except StopIteration, _e:
# subiterator exhausted on first poll
# extract return value
_r = _e.args
if not _r: _r = (None,)
else:
# if subgenerator is another supergenerator
# extract the root of its gen_yf shared_stack
try:
_iyf = _i.gi_frame.f_locals['gen']
except (AttributeError,KeyError):
_iyf = []
else:
_iyf = _yieldingfrom.get(_iyf,[])
if isinstance(_iyf, _stack):
_iyf = _iyf.root()
gen_yf.push(_i, _iyf)
# INNER loop
while True:
if _iyf is None:
# subiterator was adopted by caller
# and is now exhausted
item = _y
break
try:
# yield what the subiterator did
_s = (yield _y)
except GeneratorExit, _e:
# close as many subiterators as possible
while gen_yf:
_i, _iyf = gen_yf.top()
try:
_close = _i.close
except AttributeError:
pass
else:
_close()
gen_yf.pop()
# finally clause will gen.close()
raise _e
except BaseException:
# caller did wrapper.throw
_x = _exc_info()
# throw to the subiterator if possible
while gen_yf:
_i, _iyf = gen_yf.top()
try:
_throw = _i.throw
except AttributeError:
# doesn't attempt to close _i?
# try throwing to subiterator's parent
pass
else:
try:
_y = _throw(*_x)
except StopIteration, _e:
_r = _e.args
if not _r: _r = (None,)
# drop to INTERSECTION A
# then to INTERSECTION B
break
else:
_r = None
# drop to INTERSECTION A
# then to INNER loop
break
gen_yf.pop()
else:
# if gen raises StopIteration
# or any other Exception, we propagate
_y = gen.throw(*_x)
_r = _iyf = None
# fall through to INTERSECTION A
# then to INNER loop then to OUTER loop
pass
# INTERSECTION A
# restart INNER loop or proceed to B?
if _r is None: continue
# caller did send/next
else:
if not gen_yf:
# subiterator was adopted by caller
# and is now exhausted
_r = (_s,)
_iyf = None
# fall through to INTERSECTION B
pass
else:
if _iyf:
# check if current _i itself
# now yielding from a subiterator?
_i, _iyf = gen_yf.top()
try:
# re-poll the subiterator
if _s is None:
_y = _i.next()
else:
_y = _i.send(_s)
except StopIteration, _e:
# subiterator is exhausted
# extract return value
_r = _e.args
if not _r: _r = (None,)
# fall through to INTERSECTION B
pass
else:
# restart INNER loop
continue
# INTERSECTION B
# done yielding from active subiterator
# send retvalue to its parent
while True:
if _iyf is not None:
gen_yf.pop()
if gen_yf:
_i, _iyf = gen_yf.top()
try:
# push retval to subiterator's parent
_y = _i.send(_r[0])
except StopIteration, _e:
# parent is exhausted, try _its_ parent
_r = _e.args
if not _r: _r = (None,)
continue
else:
# fall through to INTERSECTION C
# then to INNER loop
pass
else:
# gen_yf is empty, push return value to gen
# if gen raises StopIteration
# or any other Exception, we propagate
_y = gen.send(_r[0])
_iyf = None
# fall through to INTERSECTION C
# then to INNER loop then to OUTER loop
pass
# INTERSECTION C
# passed retvalue, continue INNER loop
break
# traditional yield from gen
else:
try:
sent = (yield item)
except Exception:
# caller did wrapper.throw
_x = _exc_info()
# if gen raises StopIteration
# or any other Exception, we propagate
item = gen.throw(*_x)
else:
# if gen raises StopIteration
# or any other Exception, we propagate
item = gen.send(sent)
# end of OUTER loop, restart it
pass
finally:
# gen raised Exception
# or caller did wrapper.close()
# or wrapper was garbage collected
gen.close()
return wrapper
|
http://www.python.org/dev/peps/pep-0380/ proposes new syntax ("yield from") for generators to delegate control to a "subgenerator" (really to any iterator). Any send/next/throw/close calls to the delegating generator are forwarded to the delegee, until the delegee is exhausted.
This is being considered for inclusion in Python 2.7, but I wanted a way to play around with the design pattern now (and in case the PEP isn't soon accepted, and on older Python installations regardless of what happens with future versions of Python).
So I came up with this decorator-based solution. The "supergenerator" decorator wraps the delegating generator with a control handler that takes care of directing send/next/throw/close calls to the delegator or delegee, as appropriate.
Sample usage is described in the decorator's docstring.
Delegees can pass return values to the "yield _from" call by "raise StopIteration(retval)". Example:
@supergenerator
def gen1funct():
for i in xrange(3):
sent = yield i
print "sent1: %r" % (sent,)
delegee = gen2funct()
retval = yield _from(delegee)
print "return value: %r" % (retval,)
def gen2funct():
for i in xrange(3,6):
sent = yield i
print "sent2: %r" % (sent,)
raise StopIteration(100)
gen=gen1funct()
try:
i = gen.next()
while True:
print "yielded: %r" % (i,)
i = gen.send(i*10)
except StopIteration:
print "yielded: %r" % (i,)
print "stopped"
Result:
yielded: 0
sent1: 0
yielded: 1
sent1: 10
yielded: 2
sent1: 20
yielded: 3
sent2: 30
yielded: 4
sent2: 40
yielded: 5
sent2: 50
return value: 100
yielded: 5
stopped
This is the "optimized" version of my implementation. It automatically keeps track of nested "yield _from"s, and delegates directly to the most deeply-nested delgees.
There's also a "simple" version which doesn't do any special handling of nested "yield _from"s. It's easiest to understand the code by first reading the "simple" version (at http://code.activestate.com/recipes/576727/) and then following how this version differs.