[Tutor] does id function return location of reference or the referenced object?

Kent Johnson kent37 at tds.net
Fri Mar 6 18:18:31 CET 2009


On Fri, Mar 6, 2009 at 12:09 PM, Serdar Tumgoren <zstumgoren at 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


More information about the Tutor mailing list