python terminology on classes

John Nagle nagle at animats.com
Tue Jul 27 13:28:19 EDT 2010


On 7/27/2010 12:17 AM, Bruno Desthuilliers wrote:

>> destructor
>
> Python has no real destructor. You can implement a __del__ method that
> will _eventually_ be called before the instance gets garbage-collected,
> but you'd rather not rely on it. Also, implementing this method will
> prevent cycle detection.

    That's not correct.  The Python language reference is at
"http://docs.python.org/reference/datamodel.html".  In CPython,
either __del__ will be called when the reference count goes to
zero, or it won't be called at all.  The garbage collector that
backs up the reference counting system doesn't delete objects with
__del__ methods, because of the usual problems with deletion from
a garbage collector.  The defined semantics are that loop-free
structures are deleted properly, but loops with one object that
has a __del__ hang around forever.  You can use weak pointers to
avoid loops.

    IronPython and ShedSkin are garbage-collected implementations which
have quite different __del__ semantics.  That's considered non-standard.

    In C++, the RAII approach is popular and recommended.
In C++, it's routine to create local objects which, when they go out
of scope, close a file, unlock a lock, or close a window.
It's also widely used in Python, but it's now somewhat deprecated.

    Python 2.6 has a recently added "with" clause, borrowed from
LISP, for associating actions with scopes.  This is supported for
files and locks, but setting your own object up for "with"
requires adding special methods to the object.  "with" is less
convenient and more limited than RAII, but that's the direction
Python is going.  This may be in preparation for a move to a real
garbage collector.

				John Nagle



More information about the Python-list mailing list