Extracting elements over multiple lists?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Nov 15 17:21:41 EST 2011
On Tue, 15 Nov 2011 17:01:23 +0000, Prasad, Ramit wrote:
> Can you expand on why 'del' is "tricky"/misleading?
People often imagine that the del statement sends a message to the object
"please delete yourself", which then calls the __del__ method. That is
incorrect.
"del x" is an unbinding operation, it removes the *name* "x" from the
current namespace. As a side-effect, if the object which was bound to x
no longer has any other references to it, then the garbage collector will
delete it and __del__ may be called.
(I say "may be called" rather than "will" because there are circumstances
where __del__ methods won't get called, such as during interpreter
shutdown.)
On the other hand, "del x[i]" does work like the way people expect. It
deletes items from collections (lists, dicts, etc.) and does so by
calling the method x.__delitem__(i). This also may cause the garbage
collector to delete the object which was at x[i] if that was the last
reference to that object.
CPython's implementation keeps a count of references for each object, and
the garbage collector deletes the object immediately that reference count
reaches zero. This is fast, simple, deterministic (objects will be
predictably deleted as soon as they can be), but simple-minded, and so it
is aided by a second garbage collector which runs periodically, looking
for reference cycles. You can set how often this second garbage collector
runs using the gc module.
Jython uses the Java garbage collector, and IronPython the .Net garbage
collector. Neither are reference counters, and (as far as I know) neither
guarantees that objects will be deleted as soon as they are free to be
deleted. They will be deleted whenever the garbage collector gets around
to it.
--
Steven
More information about the Python-list
mailing list