Python (the standard CPython, not variants like Jython, Unladen Swallow and IronPython) uses reference counting for its objects.
With that, it also has RAII and (mostly) deterministic garbage collection. For example, this is supposed to work deterministically closing files:
def a():
fp = open('/my/file', 'r')
return fp.read()
Note fp.close()
is never called. As soon as fp
goes out of scope, the object should be destroyed. However, there are some cases where deterministic finalization is not guaranteed, such as in:
- Something throws an exception and the traceback is currently being handled, or a reference is kept to it (note
sys.last_traceback
keeps the last traceback)
- Cyclic references exist in an object, causing the reference count to not go to zero
Therefore, while python theoretically has deterministic finalization, it is better to explicitly close any resources where it's possible an exception (like IOError or the like) could cause the object to remain live.