binding a reference to a variable

Andrew Koenig ark at research.att.com
Tue Apr 9 19:26:13 EDT 2002


>> Now, f is an object that I can use to rebind the name x.  For
>> example, if I execute f(42), that sets x to 42.

Aahz> You really don't want to do this in Python.

One thing that fascinates me is how the nature of a language affects
the preferred idioms therein.  To help me further my understanding,
would you mind explaining to me why this particular idea is undesirable
in Python?  I can think of several possible reasons, but I don't know
which reason is most plausible to the Python community.

Aahz>  Your best bet is to pass
Aahz> around mutable objects (namely class instances and modules) and use
Aahz> setattr().  You could be grotesque and also permit lists and
Aahz> dictionaries:

Aahz>     def updateObject(obj, key, value):
Aahz>         try:
Aahz>             obj.setattr(key, value)
Aahz>         except AttributeError:
Aahz>             obj.setitem(key, value)

Ick.  I wanna keep it simple.

I'm thinking back to Snobol, which lets you do this

        foo(.x)

This would pass the name of x to foo.  That name isn't necessarily
the same as "x", because if a is an array, you can also call

        foo(.a[i])

which passes the name of the i'th element of a to foo.

Within foo, you say

        $arg = 42

(assuming that the formal parameter is named arg), which sets
x (or a[i], depending on the call) to 42.

Incidentally, Snobol variables are just like Python variables in
that assignment is really rebinding.


-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark



More information about the Python-list mailing list