4

When coding in Python, I sometimes use this syntax :

open(filename,'w').write("sometext")

As far as I know this causes Python's garbage-collector to close the file, but I've heard that the behavior of the GC is not defined and that might be problematic.

Is that true ? Should I always use this :

with open(filename) as f: 
   f.write()
oyon
  • 81
  • 3
  • I've edited your question since this doesn't really have anything to do with "naming files" and was confusing. However if you disagree feel free to rollback my edit. –  May 11 '14 at 18:15
  • this is not exactly the same, using unnamed open (without saving the file to an object) there is no need for the GC to do reference count. as the file object is never saved to the local namespace. – oyon May 11 '14 at 18:20
  • @user1614719: it's called reference counting, not name counting. Even if you don't have a variable in the local namespace, it still counts as a reference to prevents the file from being cleaned up until the method call finishes. – Lie Ryan May 11 '14 at 18:21
  • Also, I believe you're referring to "naming files" as in giving a "variable name to the file", while Andre is referring to "giving a filename in the filesystem". Your title is confusing/misleading, IMO. – Lie Ryan May 11 '14 at 18:23

1 Answers1

3

Do not confuse garbage-collection and reference-counting.

While not formally guaranteed, in CPython at least, using open(...).write(...) would result with the desired behavior, because after the line completes, the ref-count of the file object drops to 0, and it is deleted immediately.

That being said, DON'T do it. It is way more elegant/readable/pythonic to use the with statement, and explicit is better than implicit.

shx2
  • 61,779
  • 13
  • 130
  • 153
  • 1
    is that truly a specific behaviour to Cpython? – oyon May 11 '14 at 18:22
  • 1
    @user1614719: yes, but it's not a guaranteed behavior either. A future version of CPython might decide to do away with reference counting and use garbage counting all the way, like Jython and IronPython. – Lie Ryan May 11 '14 at 18:25