It's a bug!....but is it me or the script? (Global var assign)
Peter Otten
__peter__ at web.de
Wed Nov 19 11:25:33 EST 2003
Halfdan Holger Knudsen wrote:
> Hey here's a relatively simple question...the code is for a mock-up
> passwd, usrname dict storagesystem. Why doesn't the variable enc behave
> globally (the admin function turns up a "local var referenced before
> assignment" error, when inputting 's')? In all likelyhood I've just
> managed to stare myself blind, so to anyone w/ a spare pair of eyes - the
> help would be appreciated. It's run under Python 2.3.0 in Win2k.
>
> T/x
> H
>
> PS: I know it's long and I apologize, but basically it's just the first 8
> lines that should matter.
When you try to make it shorter instead of staring yourself blind the chance
of finding the bug yourself increases rapidly:
>>> e = 0
>>> def fun():
... if e == 0:
... e = 1
...
>>> fun()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in fun
UnboundLocalError: local variable 'e' referenced before assignment
>>> def fun():
... global e
... if e == 0:
... e = 1
...
>>> fun()
>>> e
1
>>>
When you are rebinding a name (enc) anywhere inside a function it refers to
a local even before the actual rebinding is done, unless you explicitly
state you want it to refer to a global, i. e. say
global enc
Peter
More information about the Python-list
mailing list