Inspired by this question.
Why is there no list.clear() method in python? I\'ve found several questions here that say the correct way to do it is one of the followin
I can't answer to the why; but there absolutely should be one, so different types of objects can be cleared with the same interface.
An obvious, simple example:
def process_and_clear_requests(reqs):
for r in reqs:
do_req(r)
reqs.clear()
This only requires that the object support iteration, and that it support clear(). If lists had a clear() method, this could accept a list or set equally. Instead, since sets and lists have a different API for deleting their contents, that doesn't work; you end up with an unnecessarily ugly hack, like:
def process_and_clear_requests(reqs):
for r in reqs:
do_req(r)
if getattr(reqs, "clear"):
reqs.clear()
else:
del reqs[:]
As far as I'm concerned, using del obj[:] or obj[:] = [] are just unpleasant, unintuitive hacks to work around the fact that list is missing clear().
This is taking "reducing redundancy" to a fault, where it damages the consistency of the language, which is even more important.
As to which you should use, I'd recommend del obj[:]. I think it's easier to implement for non-list-like objects.
While there was no list.clear()
when this question was asked, 3.3 now has one (as requested in http://bugs.python.org/issue10516). Additionally, clear()
methods have been added to bytearray and MutableSequence to ease switching between lists and other collections (set, dict etc).
Full details of the change can be found here.
In the threads you linked Raymond Hettinger pretty much sums up the pros and cons of adding that method. When it comes to language design, it's really important to be conservative. See for example the "every feature starts with -100 points" principle the C# team has. You don't get something as clean as Python by adding features willy-nilly. Just take a look at some of the more cruftier popular scripting languages to see where it takes you.
I guess the .clear()
method just never did cross the implicit -100 points rule to become something worth adding to the core language. Although given that the methodname is already used for an equivalent purpose and the alternative can be hard to find, it probably isn't all that far from it.
The question should be why clear
was deemed necessary in the first place. The following works to clear any Python collection that I can think of.
def clear(x):
return type(x)()
>>> s = {1, 2, 3}
>>> s
set([1, 2, 3])
>>> s = clear(s)
>>> s
set([])
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> l = clear(l)
>>> l
[]