bug in python's scope handling?

Steve Holden sholden at holdenweb.com
Wed Jul 18 14:20:49 EDT 2001


"Philipp Weinfurter" <philipprw at gmx.at> wrote in message
news:slrn9lbkhg.1at.philipprw at chello213047126184.14.univie.teleweb.at...
> hi everyone!
>
> a = 1
>
> def func1():
>     b = a + 1
>
> right, the local variable b is assigned the value of the global variable
> a. so far, so good.
>
> def func2():
>     a = a + 1
>
> and now the local variable a is assigned... uh, nothing because it
produces
> an UnboundLocalError.
>
> now, i admit that no programmer should ever write such code, but i still
> consider this a bug. what _should_ happen, is this: the right side of
> the assignment is evaluated first, thus adding 1 to the value of the
global
> variable a, then the result should be assigned to the local variable a,
> no?
> then

When your Python is compiled into bytecode, the assignment to a is detected
during compilation of your function func2(). The name a is therefore assumed
to refer to a local variable, hence the ruin-time exception you observe.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list