Question re local bindings in nested scopes

Greg Ewing greg at cosc.canterbury.ac.nz
Thu Jun 7 23:11:00 EDT 2001


Kirby Urner wrote:
> 
> But should a=a+1 (or a += 1) really break the initial binding of a
> to the outer scope?  Is this intended?

I'd say it's "not unintended". :-)

It's simply a consequence of the rule that any assignment
to a variable in a given scope makes it local to that
scope. This rule does lead to surprises in some cases,
but that's the price Python pays for not requiring
variables to be declared.

> it seems odd to unbind an already initialized variable 

"Unbinding" is the wrong word. The outer binding is still
there, it's just being shadowed by an inner one. 

> just because we add 1 to it. 

It's not because you're adding 1 to it, it's because
you're *assigning* to it. Remember that += and friends 
are forms of assignment.

> Seems too subtle for its own good.

The alternative you seem to want would have subtleties of 
its own. What do you think this should do:

  def f(a,b):
    def g():
      if b:
        z = a
      else:
        z = 0
      a = z + 1
    g()
    return a

Under one possible interpretation, a would be local or
not depending on the value of b. I think Tim and Guido
would regard that as rather too subtle!

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list