UnboundLocalError on shadowed import
Peter Hansen
peter at engcorp.com
Wed Jun 30 08:15:25 EDT 2004
vincent wehren wrote:
> Peter Hansen wrote:
>
>> It "has to" raise an exception. The use of "sys" inside the function
>> is local (because you assign to it, because "import sys" is effectively
>> an assignment). Locals are not handled quite the same as other names,
>> as you know -- they are turned into index lookups in a list instead of
>> hash lookups in a dictionary. The interpreter can't know that your use
>> of sys.exit(0) is supposed to refer to the global sys, because all uses
>> of "sys" are really just "local variable number 3" or something like
>> that inside the function.
>>
>> Basically, "don't do that" is about the best you'll get, I think.
>
> Well, just for the sake of it, there still is the obvious option of
> adding the line "global sys" before sys.exit(0) to tell the interpreter
> to use the "globally imported sys".
Which basically amounts to "not doing that". ;-) You're right...
More information about the Python-list
mailing list