[pyar] Curiosidades del Python

Alejandro Santos listas en alejolp.com
Lun Oct 24 23:57:09 ART 2011


2011/10/24 Roberto Alsina <ralsina en netmanagers.com.ar>
>
> Ojeando el manual de Nuitka (http://t.co/MLvCt6nR) me crucé con esta lindura:
>
> >>> def f():
> ...     x = (i for i in (yield) if (yield))
>
> >>> a=f(); print a
> <generator object f at 0x02269CB0>
> >>> a.next(); print a
> <generator object f at 0x02269CB0>
> >>> a.next(); print a
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "<stdin>", line 2, in f
> TypeError: 'NoneType' object is not iterable
> >>> a.next(); print a
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> StopIteration
>
>
> Que les parece? Porqué hace eso? Porque alguien querría hacer eso?
>

Qué loco, yield es una expresión. Siempre creí que era un statement.
Dando vueltas un rato por la doc de Python llegué al PEP 342. La idea
es poder comunicarse ida y vuelta con el generator, no solo que el
yield "dispare" valores sino tambien que los reciba de afuera.

>>> def f():
...     a = (yield)
...     print "a: ", a
...
>>> b = f()
>>> b.next()
>>> b.send("asd")
a:  asd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Copio la parte interesante del PEP 342, http://www.python.org/dev/peps/pep-0342/

  1. Redefine "yield" to be an expression, rather than a statement.
       The current yield statement would become a yield expression
       whose value is thrown away.  A yield expression's value is
       None whenever the generator is resumed by a normal next() call.

    2. Add a new send() method for generator-iterators, which resumes
       the generator and "sends" a value that becomes the result of the
       current yield-expression.  The send() method returns the next
       value yielded by the generator, or raises StopIteration if the
       generator exits without yielding another value.


--
Alejandro Santos



More information about the pyar mailing list