binding a reference to a variable

Bengt Richter bokr at oz.net
Wed Apr 10 21:51:08 EDT 2002


On Wed, 10 Apr 2002 21:30:08 GMT, Andrew Koenig <ark at research.att.com> wrote:

>Bengt> What about x() as the spelling of get-x's-value and x(v) as the
>Bengt> spelling of set-x's-value-to-v-and-return-v?
>
>That still assumes that the value of x was set previously.
>
x as container, yes

>If I make that assumption, there are lots of ways of solving the
>problem -- the first one I suggested was simply to set x to [].
>
yes, I was in effect just suggesting eliminating the need for a set
function in the expressions if a named container was going to exist anyway.

If you need to introduce new names into a namespace as a side effect
of an expression evaluation, does it have to be the local namespace,
or could you live with a name space identifier as part of your expression?

The local namespace is going to be a problem in general, but if you are
experimenting, perhaps the restrictions on locals() will make it ok for
you to use

 >>> def set(name, val, ns=locals()):
 ...     ns[name]=val
 ...     return val
 ...
 >>> z
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 NameError: name 'z' is not defined
 >>> set('z',123)
 123
 >>> z
 123

Note that z wasn't preset, and set was executed as an expression.

But if you need to depend on this, maybe Guido will make a pronouncement
as to what functionality will be guaranteed for locals() and globals().

(I've been told that locals() worked for me in similar usage "... "by accident"
in a given implementation, in a certain restricted context, because a undefined
behavior happens to be that way in said specific implementation." So beware ;-)

Of course, def set ... must be executed where it can capture ns=locals()
for use inside the function, where locals() is another space (and read-only).

If you could live with a name space identifier, you obviously have all
sorts of options. Does your problem preclude that way?

Other nasty tricks to create a new bare visible symbol from an expression could be
based on globals() in place of locals(), or even setattr(__builtins__, name, val),
though the latter particularly seems not very advisable ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list