[Python-ideas] set.add() return value
Guido van Rossum
guido at python.org
Tue Feb 17 03:32:55 CET 2009
On Mon, Feb 16, 2009 at 6:13 PM, Raymond Hettinger <python at rcn.com> wrote:
> [Steven D'Aprano]
>>
>> What's the use-case for this? What's wrong with doing this?
>>
>> if 42 in myset:
>> myset.add(42)
>>
>> Short, sweet, and doesn't require any new methods.
>
> I think you meant: "if 42 not in myset".
>
> Am -1 on the proposed change.
> AFAICT, it will never save more than one line of code.
> The current version is explicit and clear.
> Moreover, it does not require special knowledge to read.
>
> Currently, the set API has a zero learning curve and doesn't
> demand that you remember a rule particular to Python.
> In contrast, the proposed version requires that you know
> that Python has a special API and you need to remember that
> when you're reading someone else's code.
>
> Give this snippet to five Python programmers (not in this thread)
> and see if they correctly deduce when f(x), f(y), f(z), and f(m) will
> be called. Also, see if they can correctly assert known post-conditions
> (after each if-statement and before each function call).
>
> if(not myset.add(x)):
> f(x)
> else:
> g(x)
> if(myset.discard(y)):
> f(y)
> else:
> g(y)
> if(myset.update(z):
> f(z)
> else:
> g(z)
> if(myset):
> f(m)
> else:
> g(m)
Point taken, but...
> As I mentioned in another post, this API is counterintuitive for
> anyone who is used to other languages where operations like
> set.add() always returns self and lets them write code like:
>
> myset.add(x).add(y).add(z)
Which language has that?
> Essentially the argument against boils down to there not being
> an intuitively obvious correct interpretation of what the code
> does while the existing approach is crystal clear.
>
> The set API currently has no rough edges. It is one of the cleanest
> APIs in the language and I hope it stays that way.
Hey Raymond, relax. You don't have to take it personal.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-ideas
mailing list