[Python-ideas] set.add() return value

Steven D'Aprano steve at pearwood.info
Wed Feb 18 00:01:22 CET 2009


Bill Janssen wrote:
> Guido van Rossum <guido at python.org> wrote:
> 
>> This example also has a bug, which neither of the two posters
>> responding caught (unless Bill J was being *very* subtle).
> 
> Sorry, I should have been more brutal.  To my mind, the fact that Steve
> got it wrong was a nice illustration of how much extra mental effort
> needed to be expended because the feature Ralf suggests wasn't
> available.

I'm not excusing my sloppiness, but I think that my mistake is an 
argument against the proposal that add (or in Greg's case, test_and_add) 
should return True if the object was *not* added (because it was already 
there). In other words, despite Greg's suggested name:

was_it_there = myset.test_and_add(42)

I was confused by my intuition that the return flag should mean the 
object was added, and then made the mental translation:

test_and_add() returns True => 42 was added to the set

became:

42 in set returns True => 42 is to be added to the set

which is of course the opposite intention to the proposal but in the 
brief time I spent writing the email easy to make.

I believe that some people will expect to use it like this:

if set.test_and_add(42):
     print "42 was not added because it was already there."

and others like this:

if set.test_and_add(42):
     print "42 was added because it wasn't there."

and yet others (I expect the majority, including me) will flip from one 
to the other and consequently find that 50% of the time they get it wrong.

I think that test_and_add is naturally two operations, not one, and 
forcing it to be one operation will just lead to confusion.



-- 
Steven




More information about the Python-ideas mailing list