[Python-Dev] Returning None from methods that mutate object state

Terry Reedy tjreedy at udel.edu
Sat May 17 10:26:12 CEST 2014


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'.

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.

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.)

> That's a deliberate design choice, and one that has been explained a
> few times on the list when folks ask why "[].sort().reverse()" doesn't
> work when "'ABC'.lower().replace('-', '_')" does.

Do people ask why sys.stdout.write(line).write('\n') does not work?

> Would it be worth adding such a note? Or is it out of scope?

-- 
Terry Jan Reedy



More information about the Python-Dev mailing list