binding a reference to a variable

Aahz aahz at pythoncraft.com
Tue Apr 9 18:25:41 EDT 2002


In article <yu994rikfzh5.fsf at europa.research.att.com>,
Andrew Koenig  <ark at research.att.com> wrote:
>
>I would like to be able to write an expression that yields an
>object that I can subsequently use to rebind a name that I mention
>only in that expression.  How do I do it?
>
>Here's a function definition:
>
>        def f(v):
>                global x
>                x = v
>
>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.

You really don't want to do this in Python.  Your best bet is to pass
around mutable objects (namely class instances and modules) and use
setattr().  You could be grotesque and also permit lists and
dictionaries:

    def updateObject(obj, key, value):
        try:
            obj.setattr(key, value)
        except AttributeError:
            obj.setitem(key, value)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"There are times when effort is important and necessary, but this should
not be taken as any kind of moral imperative."  --jdecker



More information about the Python-list mailing list