Basic Python Query

Chris Angelico rosuav at gmail.com
Fri Aug 23 11:50:51 EDT 2013


On Fri, Aug 23, 2013 at 5:12 PM, Ulrich Eckhardt
<ulrich.eckhardt at dominolaser.com> wrote:
> Am 23.08.2013 05:28, schrieb Steven D'Aprano:
>>
>> On Thu, 22 Aug 2013 13:54:14 +0200, Ulrich Eckhardt wrote:
>>>
>>> When the Python object goes away, it doesn't necessarily affect
>>> thethread or file it represents.
>>
>>
>> That's certainly not true with file objects. When the file object goes
>> out of scope, the underlying low-level file is closed.
>
>
> Ahem, yes, but no: Calling close(fd) is not the same as destroying the file,
> I'm pretty sure it's still on my harddisk after that. That is also the
> difference to strings, where the Python object really is all there is to it.
> Similarly you can only customize the Python side of things with derivation,
> the other side will remain the same, apart from the data you write to the
> file or the code you run in the thread.

The file object doesn't represent the file on the disk; it represents
the "open file", which is a thing that you can have a handle (file
descriptor) to. That "thing" is indeed destroyed when the file object
is __del__'d, though it's possible to dispose of it sooner than that:

>>> f = open("test","w")
>>> with f:
	f.write("Hello, world!")

13
>>> f
<_io.TextIOWrapper name='test' mode='w' encoding='cp1252'>

f has been closed at this point, and if I now go to open it in another
application, Python won't hold any locks; but the object still exists.
However, the general expectation is that the file object and the
open-file in the OS will correspond.

ChrisA



More information about the Python-list mailing list