1

I know

with open(my_file, 'r') as f:
    pass

opens and closes the file. Also,

f = open(my_file, 'r'); f.close()

does the same.

What about this:

open(my_file, 'r')

My actual question case is this:

import json;
json.load(open(my_file, 'r')) 

vs

import json;
with open(my_file, 'r') as f:
    j = json.load(f)

I guess that technically, the file should stay open, but I'm pretty sure that since the file object was not assigned, it was closed right away, by Python's garbage collector.

  1. Am I right?
  2. Is this a good practice?
  3. Any difference between Python versions here?
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • It should, but then you don't have a handle to close it. I can't see any benefit to not assigning it. – Carcigenicate Aug 19 '19 at 18:33
  • 1
    Maybe more info here: https://stackoverflow.com/questions/1834556/does-a-file-object-automatically-close-when-its-reference-count-hits-zero – Andrej Kesely Aug 19 '19 at 19:52

1 Answers1

5

I'm pretty sure that since the file object was not assigned, it was closed right away.

In CPython implementation, the object returned by open will be deleted once the reference count decreases to zero. This is independent of garbage collector, and will happen even if GC is turned off. In the case of json.load(open(my_file, 'r')) the file handle will be closed right away, since exiting the body of json.load will release the only reference.

Is this a good practice?

No. It relies on implementation details of CPython that the file handle will be closed in a timely manner. It's a "code smell", people reading your code might assume you are a sloppy programmer. Use the with statement to ensure the timing of the closure is made explicit. If you just prefer the way a one-liner looks, then you can use pathlib, like this:

json.loads(Path(my_file).read_text())

Any difference between Python versions here?

No.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    It's worth emphasizing that even on CPython not explicitly closing the file can lead to surprising bugs since the file closure doesn't necessarily happen "locally" to where the file is actually used. This can be especially problematic on Windows where there are stronger restrictions on what you can do with files that have open handles to them. – Iguananaut Aug 19 '19 at 19:03