0

If I'm going to pass an open(filename) object directly as argument to another method, say json.load(), in this way:

data = json.load(open("filename.json"))

can I be sure that the open stream is garbage-collected, thus closed, as soon as json.load() finishes its execution, or I'm going to face corruption issues very soon?

I know the best practice would be with open(filename) as f: syntax, but what if I insisted for a one-liner solution?

Max Shouman
  • 1,333
  • 1
  • 4
  • 11
  • If you're so insistent on a one-liner, you can just shove the whole `with` into one line: `with open(filename) as f: data = json.load(f)`. – user2357112 Jul 14 '21 at 21:51
  • Does this answer your question? [Is explicitly closing files important?](https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important) – mkrieger1 Jul 14 '21 at 21:52
  • @user2357112supportsMonica That's actually a good workaround! I've read somewhere that one-liner indentations are bad for PEP but i can ignore it in this case. Still it's interesting to know what happens to that file object in memory. – Max Shouman Jul 14 '21 at 21:58
  • 1
    @MaxShouman no, that's an *absurd* workaround, because it's not working around anything except an irrational need to make something a one-liner. – juanpa.arrivillaga Jul 14 '21 at 22:00
  • @mkrieger1 it was very interesting to read and it's a general overview of a broad problem, but it doesn't focus on my specific case, i.e. the file is implicitly assigned to a function local var; when the function is done with its task theorically the name is removed and being the only one reference to the object, it should be removed (according to CPython, but portability is not a problem in my case). – Max Shouman Jul 14 '21 at 22:01
  • 1
    In any case, in Python, objects are free for garbage collection when their reference count reaches zero. As long as the function you are using is free of side-effects that might silently create a reference, e.g. appending the object to some list in the global scope, then as soon as the function returns, local references cease to exist and the object is no-longer referenced anywhere, and it is free for garbage collection – juanpa.arrivillaga Jul 14 '21 at 22:02
  • @juanpa.arrivillaga it might be irrational, but what is the problem with preferring more concise solutions if they don't bring further problems? – Max Shouman Jul 14 '21 at 22:04
  • @juanpa.arrivillaga thank you for the explanation btw, that's exactly what I needed to know! – Max Shouman Jul 14 '21 at 22:05

0 Answers0