Rebindings [was Re: Favorite non-python language trick?]

Bengt Richter bokr at oz.net
Sun Jun 26 18:48:14 EDT 2005


On Sun, 26 Jun 2005 14:36:42 +1000, Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:

>On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote:
>
>>>Using := and = for assignment and equality is precisely as stupid as using
>>>= and == for assignment and equality. Perhaps less stupid: why do we use
>>>== for equals, but not ++ for plus and -- for minus?
>>>
>> I agree, but I think := would be nice in python for RE-binding an existing
>> binding, wherever it is seen from the local context. Thus you could
>> write
>> 
>>     def foo(): x:=123
oops, for below example, needs global declaration
       def foo():
           global x
           x:=123  #note that x:=123 searches outward through nested scopes,
                   #not including globals unless explicitly declared, whereas
           # x=456 would always {re}bind the global x, as usual with a global x declared.
>> 
>> and
>>    x = 456
>>    def bar():
>>        x = 789
>>        foo()  # finds and rebinds local x
>>        print x
>>    bar() # -> 123
>>    print x # -> 456
>>    foo()      # finds and rebinds the global x
oops, not so, unless foo has correction above
>>    print x # -> 123
>> 
>> but
>>    del x
>>    foo()  #-> NameError exception, can't find any x to rebind
>> 
>> hm, wandered a bit OT there, ;-/
>
>Given how much the use of global variables are discouraged, is it a
>good idea to allow even more inter-namespace interactions?
>
I forgot some of my previous thoughts on this. It's not as wild as it appears ;-)

I forgot to mention that of course a symbol found in __builtins__ by way
of the usual default lookup should not be rebound. And only globals explicitly
declared should be rebound (error in code above, since foo doesn't have global x).
So that limits it to the local scope and nested scopes and declared globals not
preempted by nearer nested scope variable names.

This is motivated by currently not being able to rebind a closure variable in
a nested scope, and the requirement of pre-existence within a limited range of
namespaces that can (I think ;-) be statically analyzed for is meant to prevent
new accidental collision problems.

Regards,
Bengt Richter



More information about the Python-list mailing list