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 infoo()raises exception, , bug insum()raises exception before starts iterating on argument. exception expect see? i'd surprised if 1 insum()raised rather 1 infoo(), since callfoo()part of argumentsum(), , expect arguments processed before function called.otoh, in
sum(bar(x) x in foo()),sum(),foo()bugfree,bar()raises exception, have no choice delay callbar()untilsum()starts iterating -- that's part of contract of generators. (they nothing untilnext()method first called.)
see rest of section further discussion.
Comments
Post a Comment