List mutation method gotcha - How well known?

Lie Lie.1296 at gmail.com
Fri Mar 14 14:32:41 EDT 2008


On Mar 14, 4:57 pm, Jarek Zgoda <jzg... at o2.usun.pl> wrote:
> Lie napisa³(a):
>
>
>
> >> foo = [1,2,3,4]
> >> x = foo.append(5)
> >> print x
>
> >> What will be the output (choose one):
>
> >> 1)  [1,2,3,4]
> >> 2)  [1,2,3,4,5]
> >> 3)  That famous picture of Albert Einstein sticking out his tongue
> >> 4)  Nothing - no output
> >> 5)  None of the above
>
> >> I undertake to summarise answers posted to complete this "survey".
>
> > I think I'll choose 3. Well, no, I suppose the correct behavior
> > _should_ be undefined (i.e. what it returns is an implementation
> > details that should not be relied on). The fact that it returns None
> > is just a "coincidence" that happens to happen every time you tested
> > it (you can't prove by ignorance)
>
> I think in Python there's no notion of "void" return type. Deliberate
> choice to return None for functions that modify objects in place seems
> to be OK as long as it is used consistently and documented. Which is the
> case.

No, there is no need for "void" return type, what I meant is that
everything that's not said in the documentation should be assumed to
be an implementation detail, a method or a function that doesn't say
anything about its return type should be assumed to return an
implementation detail (which basically means: Don't rely on this). The
fact that list.append returns none is just a coincidence, you might
encounter another list.append that returns different thing some time
in the future, or the far future, or perhaps at the end of the
galaxy's life.



More information about the Python-list mailing list