On Fri, Mar 6, 2009 at 12:09 PM, Serdar Tumgoren <zstumgo...@gmail.com> wrote: > So can I ask what happens internally in python when you create open a file > object in a loop without assigning that file object to a variable? > > E.g.: > > for line in open(file.py): > print line > > In the above, is pythonimplicitly creating a reference to a file object and > using that in the for loop?
Yes, a reference to a file object is stored in a temporary variable. > Or is something else going on under the hood? > Either way, I figured that if you don't assign the file object to a > variable, then the file object is trashed by python's garbage collection > once the loop reaches end-of-file. The file is closed when the temporary goes out of scope, not when the loop exits. This is probably at the end of the function that includes the loop. This is true in CPython anyway. There is no guarantee in the language of when an object is garbage collected and other implementations have different policies. Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor