
Thanks Tim. The dict and set types _do_ have clear() methods, but not the list() type. I first ran into this sometime ago when a question was posted about it. It intrigued me because I saw what I thought was a gap. Basically I like things to be consistent. I was also wondering about garbage collection. If I have a humongous list, e.g. and "clear" it with: mylist = [] does the old content not need to be garbage collected? Might it not continue to occupy its memory for a while? OTOH do dict.clear() and set.clear() immediately free their memory or does it just get queued for garbage collection? On Thu, Feb 11, 2010 at 9:54 PM, Stephen J. Turnbull <turnbull@sk.tsukuba.ac.jp> wrote:
Gerald Britton writes:
> Thanks all for helping me understand this better. The subtly above is > something I missed. I searched the doc for a description of it but > couldn't readily find it. Tim's simple one-line statement and the > example above does it very nicely.
It's in the language reference. It is only two lines (the definition of "immutable" and the description of assignment semantics), so easy to miss. :-) There probably is some discussion in the tutorial.
> Switching gears for a moment, what is the feeling regarding the copy() > methods for dictionaries and sets? Are they truly redundant? Should > they be deprecated? Should users be encouraged to use the copy module > or just use "newdict = dict(olddict)" and "newset = set(oldset)" to > build a new dictionary or set from an existing one?
I think they are redundant. new = type(old) should be the standard idiom for an efficient shallow copy. If that doesn't serve your application's needs, use the copy module. The responsibility for discrimination is the application programmer's. Superficially this might seem to violate TOOWTDI, but actually, not. Shallow copies and deep copies are two very different "Its", and have to be decided by the app author in any case.
I don't see what .copy can add.
.clear is another matter, in terms of semantics. However, the same effect can be achieve at the cost of indirection and extra garbage:
class DictWithClear(object): def __init__(self): self.clear()
def clear(self): d = {}
# Implement other dict methods here.
This is obviously wasteful if all you want to do is add .clear to a "bare" dictionary. However, in many cases the dictionary is an attribute of a larger structure already and the only direct reference to the dictionary is from that structure. Then clearing by replacing the obsolete dictionary with a fresh empty one is hardly less efficient than clearing the obsolete contents.
There are other arguments *for* the .clear method (eg, it would be a possibly useful optimization if instead of a class with a dictionary attribute, the class inherited from the dictionary).
-- Gerald Britton