UnboundLocalError

Benjamin Niemann pink at odahoda.de
Thu Nov 9 10:26:37 EST 2006


Hello,

Camellia wrote:

> why it generates an "UnboundLocalError" when I do the following:
> 
> <code>
> ...
> def main():
>     number = number()
>     number_user = user_guess()
>     while number_user != number:
>         check_number(number = number, number_user = number_user)
>         number_user = user_guess()
> 
> UnboundLocalError: local variable 'number' referenced before assignment
> </code>
> 
> I found when I changed the number() to num() or whatever the issue
> solved
> but doesn't every function has its own namespace?
> Can anyone please explain it to me?

When Python compiles your code, it sees that you are using a local
variable 'number' in this function ('number = ...') and probably allocates
some memory for it or whatever - ask the core Python hackers for details.
When this statement is executed, the right hand side is evaluated first and
Python finds a reference to 'number'. It knows that number is a local
variable in main(), but has not been assigned yet (which would happend
after the right hand side is evaluated) - thus the error.

Even if you could get this to work, you have two 'number's in the function
with different meaning, which just makes understanding the code too
difficult.

Is number() (the global one) a function or class. I guess it's a function,
so I would suggest to name it 'get_number' (and same
for 'get_user_guess') - this makes the code more descriptive. Should it
really be a class, a common convention is to capitalize it 'Number()'.


HTH

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/



More information about the Python-list mailing list