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

Guido van Rossum guido at python.org
Wed May 21 03:40:10 CEST 2014


On Tuesday, May 20, 2014, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

> Chris Barker wrote:
>
>> 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".
>>
>
> Python has better ways of doing many of the things that
> method chaining is used for in other languages. In Java,
> for example, I often see it used as a somewhat klunky
> workaround for the lack of keyword arguments when
> initialising objects.
>
> Other than that, it seems to be mainly for stuffing
> multiple operations into one line, which is not something
> the Python style generally goes in for.
>
>  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.
>>
>
> It's not just about mutating the object, it's about a
> mutating method with a name that could also plausibly
> be the name of a non-mutating method. The canonical
> example is sort(), which, if you didn't already know,
> could equally well be mutating or non-mutating. In
> those cases, I think it's worth making it difficult
> to get wrong.


This is the key reason, by far the most important.


> This doesn't apply so much to pop(), which sounds
> much more like a mutating method than a non-mutating
> one, so it's less likely you'll make a mistake.
>
> --
> Greg
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: https://mail.python.org/mailman/options/python-dev/
> guido%40python.org
>


-- 
--Guido van Rossum (on iPad)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140520/e7c6c2bc/attachment.html>


More information about the Python-Dev mailing list