On Thu, Sep 12, 2013 at 6:41 AM, Markus Rother <pyt...@markusrother.de> wrote:
>     3. The default return value of methods is None instead of self.
>     If it was self, it would be possible to chain method calls (which
>     is called a cascade in smalltalk).
>
>
>     >>> lst = []
>     >>> lst.append(1).append(2).append(3) ## FAIL
>     Traceback (most recent call last):
>     ...
>     AttributeError: 'NoneType' object has no attribute 'append'

That's a policy decision: a method (or function) will *EITHER* return
a value, *OR* mutate its primary argument (in the case of a method,
that's self). It reduces the chances of code like this:

foo = [1, 4, 2, 8, 5, 7]
largest_digit = foo.sort()[-1]
one_seventh = ''.join(map(str,foo))

If you used sorted(foo) instead of foo.sort(), this wouldn't crash
out, and it'd do what you expect. Having foo.sort() return self would
mean this wouldn't crash, but would potentially do something
surprising.

But while I understand the reasoning behind it, I don't entirely
agree. There are times when I use Pike's sort() function [1], which
does return its mutated argument, something like this:

foo = sort(blah_blah_blah())

Why should that be split into two statements? Or alternatively, why
should an extra copy of the list be created (if you use Python's
sorted() here)? But for the new programmer, this is a convenient
safety-net, and if list.sort() worked the other way, it'd be just as
much a gotcha ("I ask for a sorted list, and it also changed the
original?!??").

ChrisA

[1] http://pike.lysator.liu.se/generated/manual/modref/ex/predef_3A_3A/sort.html
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to