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

Chris Barker chris.barker at noaa.gov
Tue May 20 18:30:47 CEST 2014


>
> >>>> [].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?
>

Is there a reference anywhere as to *why* the convention in Python is to do
it that way?

Personally, I often miss the ability to chain operations on mutable
objects, but I can only imagine that that design decision was made for good
reason. However, as I teach Python, I find I have nothing to say other than
"that's the way it's done in Python".

I note in a way that there is a bit of backwards logic:

immutable objects **have** to return something, so they naturally chain.
It's almost as if the philosophy of the language is that you don't want
chaining behavior, and it's really just a side effect of immutables that
you get it with them.

I suppose the argument could be that for mutable objects, returning None is
an indicator that you are a) working with an mutable object, and b) that
the method changes the internal state. But the .pop() example demonstrates
that a method can both return something meaningful, and change internal
state, so I'm not sure it's really a distinction worth making.

So again: is there a clear explanation of the logic behind the convention
posted somewhere?

-Chris

-- 

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140520/3a1f56b2/attachment.html>


More information about the Python-Dev mailing list