strange behavor....

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Nov 14 17:00:28 EST 2010


On Sun, 14 Nov 2010 12:23:03 -0800, Steve Holden wrote:

> What method of a does the statement
> 
>     a = something
> 
> call? I ask in genuine ignorance, and in the knowledge that you may
> indeed be able to point me to such a method.

I know the question wasn't directed at me, but here's my 2 cents worth:

It doesn't; Mark has correctly identified that difference between what he 
calls "simple assignment" (and the rest of us call "name binding"), and 
"complex assignment" (assignment to something other than a name).

This is a design choice of Python -- objects don't know what names (if 
any) they are bound to, so Python doesn't call a method on the object 
"something". Nor does it call an method on the object currently bound to 
the name "a" but about to be unbound -- what would be the point? And of 
course, the name  "a" might not yet be bound to anything, in which case 
there is nothing on the left hand side to call.

On the other hand, in the global scope, "a = something" *may* call 
globals().__setitem__('a', 'something'), although it's quite possible 
that Python may optimize that in some fashion and avoid the method call. 
But even if it did call the method, unless you can replace globals() with 
a custom dict that did something "interesting" on assignment, that's 
merely an implementation detail. And CPython, if not other 
implementations, don't call anything analogous inside functions: locals() 
is not a real dictionary and no method is called.

We (well, I *wink*) agree with Mark that name binding is different; we 
only disagree whether that difference is *conceptually* important enough 
to change 15 or 20 years of Python terminology to suit his Lisp 
sensibilities.


> I would prefer to think of
> 
>     a = something
> 
> and
> 
>     lst[i] = something
> 
> as in some sense different, because I see names as referencing locations
> in a namespace. Perhaps you can help to unify my perceptions.

Names in namespaces reference *objects* -- that the objects happen to 
have fixed locations in the heap (their memory location) is an 
implementation detail.

You know, some day in my Copious Spare Time, I'm going to write my own 
Python implementation using handles to objects instead of pointers, just 
so I can point to an implementation where objects are free to move in 
memory and don't have a fixed location :)


-- 
Steven



More information about the Python-list mailing list