generators improvement

Andrew Dalke adalke at mindspring.com
Tue Aug 19 16:26:00 EDT 2003


Oleg Leschov:
> What I think should increase the potential usefulness of a generators,
> is bi-directional data passage. This is very easy to implement, IMHO.
>
> What needs to be done is to allow yield return something - whatever was
> passed to the .next() thing from caller..
  ...
> I understand that this can be achieved by using some
> global, for instance, but hey, I used to implement generator's
functionality
> without using them, too - just make a class and make
> algorithm look horrible. The same thing, but much wordier and uglier
> looking... and that does not mean that generators are redundant.

While somewhat cumbersome, you could do (mind the bad
cut&paste - OE Express didn't like the tabs PythonWin sent over)

class State:
  def __init__(self):
     self.args = None
     self.kwargs = None

class OlegYield:
  def __init__(self, f):
     self.f = f
  def __call__(self, *args, **kwargs):
     state = State()
     args = (state,) + args
     return OlegIter(state, f(*args, **kwargs))

class OlegIter:
  def __init__(self, state, iter):
     self.state = state
     self.iter = iter
  def __iter__(self):
     return self
  def next(self, *args, **kwargs):
     self.state.args = args
     self.state.kwargs = kwargs
     return self.iter.next()

>>> def f(state, n):
...      for i in range(n):
...          yield i
...          print state.args, state.kwargs
...
>>> g = OlegYield(f)
>>> a = g(5)
>>> a.next()
0
>>> a.next(6, a=7)
(6,) {'a': 7}
1
>>> list(g(4))
() {}
() {}
() {}
() {}
[0, 1, 2, 3]
>>>

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list