[Python-ideas] yiled-from restrictions [was: x=(yield from) confusion]

Nick Coghlan ncoghlan at gmail.com
Fri Apr 10 03:54:44 CEST 2009


Jacob Holm wrote:
> Jim Jewett wrote:
> Yes, but since there is no sane way the this can work in the current
> proposal, I would rather raise a RuntimeError.

Sure there is.

E.g., suppose we have a simple file format with one header per line,
separated from the main body by a line starting with "~". Header lines
are processed on a per-line basis, but for the body, the unaltered lines
are passed back to the client:

  HeaderFinished = object()
  def process_file(f):
    for line in f:
      if line.startswith('~'):
        break
      yield process_header(line)
    yield HeaderFinished
    yield from f

For more complex cases, once caching of the methods in yield-from is
explicitly disallowed (as per my other message), you can do something like:

>>> def start(iterable, start):
...     itr = iter(iterable)
...     class TrapFirstNext(object):
...       def __iter__(self):
...         return self
...       def next(self):
...         TrapFirstNext.next = itr.next
...         return start
...     return TrapFirstNext()
...
>>> for val in start(range(2), "Hello World!"):
...   print val
...
Hello World!
0
1

So long as the PEP explicitly disallows caching of the bound methods
(which I now think it should do) you can get as creative as you like by
manipulating dynamically generated types at runtime.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list