updating a variable / scope problem

Robert Brewer fumanchu at amor.org
Thu Jul 8 16:32:55 EDT 2004


Rajarshi Guha wrote:
> def f(x):
> 
>     print 'hello'
>     c  =0
> 
>     def g(y):
>         print c
>         c = c + 1
>         print 'bye'
>     
>     g(10)
> 
> if __name__ == "__main__":
>     f(5)
> 
> running it gives me an error:
> UnboundLocalError: local variable 'c' referenced before assignment
> 
> Now, I expected that since c is defined in the caller routine 
> (ie f()) and
> g() lies in the scope of f(), g() should be able to access c.
> 
> So which scope is c local to in this example? And why 
> should'nt I be able
> to increment c (rather - how do I do it)

Once you add the line "c = c + 1", you've told Python that c should be
local to g(), since it involves a binding (assignment). It is *possible*
to get around this with, for example:

>>> def f(x):
... 	c = 0
... 	def g(y, c=c):
... 		c = c + 1
... 		print c
... 	g(10)
... 	
>>> f(5)
1

...but that is REALLY ugly, probably doesn't do what you want anyway,
and you shouldn't do it. The same goes for:

>>> def f(x):
... 	c = [0]
... 	def g(y):
... 		c[0] = c[0] + 1
... 		print c[0]
... 	g(10)
... 	
>>> f(5)
1

Give us a more concrete example, and we can advise on how to make it
more Pythonic...


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list