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

Nathaniel Smith njs at pobox.com
Sat May 17 15:39:28 CEST 2014


On Sat, May 17, 2014 at 6:14 AM, Nick Coghlan <ncoghlan at gmail.com> 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
>
> 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.
>
> Would it be worth adding such a note? Or is it out of scope?

Numpy also has a menagerie of in-place and out-of-place methods that
follow this convention, and we also have to go round on the mailing
list from time to time explaining to well-meaning beginners why for
the in-place methods returning None is the right ("Pythonic") design.
Having a canonical explanation of this to link to would be useful.

-n

-- 
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org


More information about the Python-Dev mailing list