UnboundLocalError on shadowed import

vincent wehren vincent at visualtrans.de
Wed Jun 30 11:10:57 CEST 2004


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".

--
Vincent Wehren



More information about the Python-list mailing list