Scope question

Diez B. Roggisch deets at nospam.web.de
Mon Aug 6 09:26:49 EDT 2007


Nitro wrote:

> Hello,
> 
> today I wrote this piece of code and I am wondering why it does not work
> the way I expect it to work. Here's the code:
> 
> y = 0
> def func():
>      y += 3
> func()
> 
> This gives an
> 
> UnboundLocalError: local variable 'y' referenced before assignment
> 
> If I change the function like this:
> 
> y = 0
> def func():
>      print y
> func()
> 
> then no error is thrown and python apparently knows about 'y'.
> 
> I don't understand why the error is thrown in the first place. Can
> somebody explain the rule which is causing the error to me?

The reason is that python's scoping rules have to somehow determine if a
variable is local to a function or part of the surrounding context.

Because python lacks variable declarations, what is does to infer the scope
of a variable is to check if it is part of the left-side of an assignment.

So in the first case, y is considered a func-local variable - which of
course you didn't initialize.

This behavior has been subject of quite a few critical discussions - yet you
have to live with it.



diez



More information about the Python-list mailing list