python - Generators and files -


when write:

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

is file opened or file system accessed when start consume generator expression?

open() called upon construction of generator, irrespective of when or whether consume it.

the relevant spec pep-289:

early binding versus late binding

after discussion, decided first (outermost) for-expression should evaluated , remaining expressions evaluated when generator executed.

asked summarize reasoning binding first expression, guido offered [5]:

consider sum(x x in foo()). suppose there's bug in foo() raises exception, , bug in sum() raises exception before starts iterating on argument. exception expect see? i'd surprised if 1 in sum() raised rather 1 in foo(), since call foo() part of argument sum(), , expect arguments processed before function called.

otoh, in sum(bar(x) x in foo()), sum() , foo() bugfree, bar() raises exception, have no choice delay call bar() until sum() starts iterating -- that's part of contract of generators. (they nothing until next() method first called.)

see rest of section further discussion.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -