binding a reference to a variable

Andrew Koenig ark at research.att.com
Tue Apr 9 15:23:18 EDT 2002


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?

My motivation is to be able to write something that is analogous
to call-by-reference in C++.

This question, as phrased, is probably a little hard to understand;
here are some examples that might help.

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.

However, this example doesn't do what I want because the
``expression'' in this example would have to be f, not the definition
of f (which isn't an expression).  The name x is not mentioned
anywhere in the expression.  Therefore, each time I want to affect a
different variable this way, I have to define a new function.

What I would really like is to be able to define a function called,
say, `set' such that set(x, 42) has the same effect as `x = 42'.

I can't use a lambda expression, because they're not allowed to
contain assignments.

So far, the closest I've been able to come is this:

        def set(var, val):
                var[:] = [val]
                
It requires that the variable in question be primed by giving it
a list as its value, and detects failure to do so:

        set(x, 42)              # error -- x is not a list
        x = []
        set(x, 42)              # x is now [42]

Is it possible to do better (i.e., to solve this problem more succinctly)?

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



More information about the Python-list mailing list