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

R. David Murray rdmurray at bitdance.com
Wed May 21 01:50:14 CEST 2014


On Tue, 20 May 2014 09:30:47 -0700, Chris Barker <chris.barker at noaa.gov> wrote:
> >
> > >>>> [].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?

I think it is exactly about not encouraging chaining of mutations, but I
could be wrong :)

--David


More information about the Python-Dev mailing list