tough-to-explain Python

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jul 7 23:02:53 EDT 2009


En Tue, 07 Jul 2009 17:04:46 -0300, kj <no.email at please.post> escribió:

> I'm having a hard time coming up with a reasonable way to explain
> certain things to programming novices.
>
>>>> ham = [1, 2, 3, 4]
>>>> spam = (ham,)
>>>> spam
> ([1, 2, 3, 4],)
>>>> spam[0] is ham
> True
>>>> spam[0] += [5]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
>>>> ham += [5]
>>>> spam
> ([1, 2, 3, 4, 5, 5],)

>
> What do you say to that?
>
> I can come up with much mumbling about pointers and stacks and
> heaps and much hand-waving about the underlying this-and-that, but
> nothing that sounds even remotely illuminating.

This article is based on an old thread in this list that is very
enlightening:

How To Think Like A Pythonista
http://python.net/crew/mwh/hacks/objectthink.html

and I'll quote just a paragraph from Alex Martelli:

«There is [...] a huge difference
between changing an object, and changing (mutating) some
OTHER object to which the first refers.

In Bologna over 100 years ago we had a statue of a local hero
depicted pointing forwards with his finger -- presumably to
the future, but given where exactly it was placed, the locals
soon identified it as "the statue that points to Hotel
Belfiore".  Then one day some enterprising developer bought
the hotel's building and restructured it -- in particular,
where the hotel used to be was now a restaurant, Da Carlo.

So, "the statue that points to Hotel Belfiore" had suddenly
become "the statue that points to Da Carlo"...!  Amazing
isn't it?  Considering that marble isn't very fluid and the
statue had not been moved or disturbed in any way...?

This is a real anecdote, by the way (except that I'm not
sure of the names of the hotel and restaurant involved --
I could be wrong on those), but I think it can still help
here.  The dictionary, or statue, has not changed at all,
even though the objects it refers/points to may have been
mutated beyond recognition, and the name people know it
by (the dictionary's string-representation) may therefore
change.  That name or representation was and is referring
to a non-intrinsic, non-persistent, "happenstance"
characteristic of the statue, or dictionary...»

-- 
Gabriel Genellina




More information about the Python-list mailing list