5 ms·
Some comments on the first example. 1. Closing a file by relying on the, nondeterministic, GC seems like a cover-up solution for sloppy programming. I've seen
by Too 13y ago
Some comments on the first example.
1. Closing a file by relying on the, nondeterministic, GC seems like a cover-up solution for sloppy programming. I've seen quite a few C# code bases where people even, instead of closing, put the equivalent of assert(self.file.closed) inside the destructor to get an early warning when someone forgets to close an external handle.
2. Why call del self.file inside __del__? If the object itself is being destroyed that means anything self refers to will be useless already and the refcount should already be decremented.
- recursive 13y agoI thought the GC in most python implementations was deterministic. According to http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection http://www.digi.com/wiki/developer/index.php/Python_Garbage_... it does use a reference counting system, which is some inconclusive evidence. Does anyone know for sure?
- ggchappell 13y agoFrom the documentation of the Python 3.3 data model[1]: > CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, .... Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (ex: always close files). > object.__del__(self) Called when the instance is about to be destroyed. This is also called a destructor. ... It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits. Summary: Don't count on it. Use "with". [1] http://docs.python.org/3.3/reference/datamodel.html http://docs.python.org/3.3/reference/datamodel.html
- ketralnis 13y agoSort of. CPython's main GC strategy is is refcounting, which is deterministic. It also does have a cycle-detecting GC that's not deterministic But this is an implementation detail, so it could change in the future. And CPython isn't the only implementation, either. IronPython, pypy, and Jython all have different GC characteristics.
- acjohnson55 13y agoReally, using a context manager and the `with` statement is usually the better way to go: http://effbot.org/zone/python-with-statement.htm http://effbot.org/zone/python-with-statement.htm
- badman_ting 13y agoRight, and since C# was brought up, a "using" statement is the equivalent way of making sure the resource is disposed of properly when it falls out of scope.