On 17 May 2014 18:26, Terry Reedy <tjre...@udel.edu> wrote: > On 5/17/2014 1:14 AM, Nick Coghlan wrote: >> >> During a conversation today, I realised that the convention of >> returning None from methods that change an object's state isn't >> captured the Programming Recommendations section of PEP 8. >> Specifically, I'm referring to this behaviour: >> >>>>> [].sort() is None >> >> True >>>>> >>>>> "ABC".lower() is None >> >> False > > > When list.pop was added, the convention was changed to > "do not return the 'self' parameter" > >>>> [1].pop() is None > False > > Not returning 'self' allows some mutation functions to return something > other than 'self'.
That's a good point - I wasn't thinking methods like pop() when phrasing it the way I did. > I phrase the rule the way I did because a recursive collections can > incidentally return itself. > >>>> L = [] >>>> L.append(L) >>>> L.pop() is L > True > > it.__next__ is another mutator that returns neither self or None. > > Actually, if one regards file read and write as mutation, then returning > None never was the rule. dict.pop() is a similar example. It was bad phrasing on my part, because I was thinking of a particular subset of mutating methods (the ones which don't have a more meaningful result that they need to return) > It seems to me that the actual Python rule is "Don't return 'self'. If there > is nothing useful to return (other than self), return None." I believe this > is true whether or not self is mutated. (Of course, there might be an > exception I have overlooked.) It's actually even more subtle than that - it's "Don't return self, unless required to do so by a protocol" (specifically, __iter__ and the _i*__ methods sometimes involve returning "self" for iterators and types that do in-place operations respectively) Cheers, Nick. -- Nick Coghlan | ncogh...@gmail.com | Brisbane, Australia _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com