[Python-ideas] set.add() return value
Guido van Rossum
guido at python.org
Tue Feb 17 02:23:35 CET 2009
[Resend, hopefully bag.python.org is fixed now.]
On Fri, Feb 13, 2009 at 5:24 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Greg Ewing wrote:
>> Chris Rebert wrote:
>>> As The Zen says: "Special cases aren't special enough to break the
>> What might be more acceptable is to add a new method
>> for this, with a name suggesting that it's more than
>> just a plain mutating operation, e.g.
>> was_it_there = myset.test_and_add(42)
> What's the use-case for this? What's wrong with doing this?
> if 42 in myset:
> Short, sweet, and doesn't require any new methods.
This example also has a bug, which neither of the two posters
responding caught (unless Bill J was being *very* subtle).
> The OP's original use-case was based on his misapprehension that key lookup
> in a set was O(N log N). I don't see any useful advantage to a new method,
> let alone a change in semantics to the existing method.
Regardless of the OP's misunderstanding, I might be +0 on changing
.add() and similar methods to returning True if the set was changed
and False if it wasn't. I don't see a serious API incompatibility
looming here (I'm assuming that the None which it currently returns is
discarded by almost all code calling it rather than relied upon). It
seems cheap enough to make this change; the internal implementation
has this information available (e.g. look at set_insert_key()). Before
I go to +1 though I would have to see that there are enough examples
found in real code that could benefit from this small optimization.
There's also the nagging concern that once we do this for set
operations people might ask to do this for dict operations too, and
then what's next. Plus, the abstract base classes would have to be
adjusted and then existing implementations thereof would become
invalid as a result. IOW the slippery-slope argument. So maybe +0 is
too string still; I'm wavering somewhere between -0 and +0 ATM.
PS Note that this is not the same case as the list.sort() method --
the latter's return value would be redundant (and IMO misleading)
while the return value for .add() provides new information. My
position on that use case is not wavering. :-)
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-ideas