File open: Is this bad Python style?

前端 未结 6 1882
庸人自扰
庸人自扰 2021-01-17 17:18

To read contents of a file:

data = open(filename, \"r\").read()

The open file immediately stops being referenced anywhere, so the file obje

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 17:59

    No, it's perfectly reasonable Python style IMO, as per your reasoning.

    Update: There are a lot of comments here about whether file objects get tidied up straight away or not. Rather than speculate, I did some digging. Here's what I see:


    From a comment in Python's object.h:

    The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement reference counts. Py_DECREF calls the object's deallocator function when the refcount falls to 0

    Looking in Python's fileobject.c:

    The function table for file objects points to function file_dealloc. This function calls close_the_file, which in turn closes the file.


    So it seems reasonable to state that at the moment, on CPython, when there are no more references to a file object, it's closed without any delay. If you think this interpretation is wrong, please post a comment indicating why you feel that way.

提交回复
热议问题