[Tutor] How is "set(ls).add('a') evaluated? [Was: Re: A program that can check if all elements of the list are mutually disjoint]

Alan Gauld learn2program at gmail.com
Sun Jun 6 07:06:37 EDT 2021


On 06/06/2021 03:32, boB Stepp wrote:
> <Gripe>
> I find it really hard to remember which functions and methods return
> "None" and operate by side effect with those that return a new object.

You are not alone. Coming from smalltalk where the default return value
of methods is self I find Python's default of none to be quite
frustrating at
times. As to when it happens the general rule is that if it is a mutable
object
that is being modified the change happens in-place and None is returned.
If it is an immutable object(string, tuple) then the "change" is returned
as a new object (since the original cannot be changed!)

But the Smalltalk style of returning self for mutables and the new object
for immutables leads to much more consistent coding style (especially
important
when dealing with heterogenous collections of objects!) and also allows
chaining.

But every language has its foibles and None returns is one of Python's.

You just have to think about whether the object being changed is mutable
or not.

-- 

Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list