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

Steven D'Aprano steve at pearwood.info
Tue Feb 17 08:36:39 CET 2009

On Tue, 17 Feb 2009 04:27:02 pm Raymond Hettinger wrote:
> [Greg Ewing]
> > I think there could be some theoretical justification
> > to do it for sets at least. The pattern of "if something
> > isn't already in some set, then add it and do some further
> > processing" turns up fairly frequently in various algorithms.
> If we have to do this, then a separate method with
> a very clear name is better than mucking-up the signature
> for set.add() and set.discard().
> Of course, we don't have to do this.  It saves only one line.

I'm with Raymond on this. I don't think it adds anything. It's not 
that saving one line is unimportant, sometimes saving one line is 
worth it. But there has to be a significant mental cost to that line 
to make it worth while, and I don't think that applies to any 
variation of:

if x in set:
    print "already there"


if set.add(x):  # or another method name if you prefer
    print "already there"

(BTW, the two above have slightly different semantics. The first 
clearly and obviously only performs the add if x is not in the set; 
the second is unclear whether the add is attempted first or not, and 
an implementation could choose either.)

Contrast Guido's description of why he likes "yield from A" compared 
to "for x in A: yield x":

Your code-reading brain has to find the correspondence between the 
loop control variable of the for-loop header and the variable yielded 
in the loop body, see that nothing else is going on, and *then* it 
can draw the conclusion about the recursive generator.
[end quote]

As far as I can see, there is no similar significant mental shortcut 
added by giving set.add() a return value.

Steven D'Aprano 
Operations Manager 
Cybersource Pty Ltd, ABN 13 053 904 082 
Level 1, 130-132 Stawell St, Richmond VIC 3121 
Tel: +61 3 9428 6922   Fax: +61 3 9428 6944 
Web: http://www.cybersource.com.au 

More information about the Python-ideas mailing list