[pyar] Diferencia entre iterar y yield, y el yield from

Facundo Batista facundobatista en gmail.com
Mie Mayo 17 14:23:02 ART 2017


Jugando con algo que se preguntó en el canal de IRC, llegué a este código:


class MyClass:
    def __init__(self):
        self.fh = open("foo.txt")

    def __iter__(self):
        for x in self.fh:
            yield x

mc = MyClass()
for line in mc:
    print("L", line, end='')
    if line == '33\n':
        break

print("--")

for line in mc:
    print("L", line, end='')


Teniendo en cuenta que...

$ cat foo.txt
11
22
33
44
55
66

Al ejecutar el código me sale:

L 11
L 22
L 33
--
L 44
L 55
L 66

¡Perfecto!

Pero ahora cambio el método __iter__ de la clase de arriba y dejo:

    def __iter__(self):
        yield from self.fh

Cuando ejecuto el código me sale:

L 11
L 22
L 33
--
Traceback (most recent call last):
  File "tfoo.py", line 32, in <module>
    for line in mc:
  File "tfoo.py", line 22, in __iter__
    yield from self.fh
ValueError: I/O operation on closed file.


Entonces, ¿cuando se cerró el archivo? ¿por qué?

Gracias! Slds.

-- 
.    Facundo

Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/
Twitter: @facundobatista


Más información sobre la lista de distribución pyar