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

Raymond Hettinger python at rcn.com
Tue Feb 17 04:14:31 CET 2009


>> 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?

I think there a several.

Smalltalk comes to mind:
'''
         addAll: aCollection
          Adds all the elements of 'aCollection' to the receiver, answer aCollection
'''

Looks like Objective C takes the same approach:
'''
  Method: IndexedCollection @keyword{-insertObject:} newObject @keyword{atIndex:} (unsigned)index
  @deftypemethodx IndexedCollecting {} @keyword{-insertElement:} (elt)newElement @keyword{atIndex:} (unsigned)index
  returns self.
'''

Also, Ruby uses the style of having mutating methods return self:

'''
 arr.fill( anObject ) -> arr
arr.fill( anObject, start [, length ] ) -> arr
arr.fill( anObject, aRange ) -> arr


 hsh.update( anOtherHash ) -> hsh

Adds the contents of anOtherHash to hsh, overwriting entries with duplicate keys with those from anOtherHash.

      h1 = { "a" => 100, "b" => 200 }
      h2 = { "b" => 254, "c" => 300 }
      h1.update(h2)  » {"a"=>100, "b"=>254, "c"=>300}

'''


I haven't checked other languages but am sure I've seen this style show-up in a number of places.


Raymond 




More information about the Python-ideas mailing list