Generators and Files

When I write:

lines = (line.strip() for line in open('a_file'))

Is the file open immediately or access to the file system when I start using a generator expression?

+4
source share
3 answers

open() called immediately after the generator is built, regardless of when or you use it.

PEP-289 Related Specification :

Early snap to late snap

After much discussion, it was decided that the first (external) expression for the expression should be evaluated immediately and that the remaining expressions are evaluated when the generator is executed.

Asking to summarize the reasoning about the binding of the first expression, Guido suggested [5]:

sum(x for x in foo()). , foo() , sum(), . ? , sum(), foo(), foo() sum(), , .

OTOH, sum(bar(x) for x in foo()), sum() foo() bugfree, bar() , , bar() , sum() - . ( , next() .)

. .

+4

. , , ( , , Python ).

, , , , :

def somefunction(filename):
    print(filename)
    return open(filename)

lines = (line.strip() for line in somefunction('a_file'))  # prints

, , :

def somefunction(filename):
    print(filename)
    for line in open(filename):
        yield line.strip()

lines = somefunction('a_file')  # no print!

list(lines)                     # prints because list iterates over the generator function.
+5

.

:

def func():
    print('x')
    return [1, 2, 3]

g = (x for x in func())

:

x

. open() , . .

+1

Source: https://habr.com/ru/post/1683964/


All Articles