binding a reference to a variable

Emile van Sebille emile at fenx.com
Tue Apr 9 23:48:48 EDT 2002


Andrew Koenig
> 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?


If you need to, you could try:

class rebind:
    def __init__(self, var, context):
        for ky, val in context.items():
            if val is var:
                self.var = ky
                break
        self.context = context
    def __call__(self, newval):
        self.context[self.var] = newval

x = 3
tx = rebind(x, globals())
tx(4)
x

although I'd be real careful where and how you deploy.  This breaks in
lots of fun-to-find ways.  After finding the first three or four, an
alternate solution or design will start looking good.

Did-Schrödinger's-cat-have-a-name?-ly y'rs

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list