UnboundLocalError on shadowed import

Peter Hansen peter at engcorp.com
Tue Jun 29 21:44:53 CEST 2004


Brad Clements wrote:
> python2.3 ~/temp/test.py
> Traceback (most recent call last):
>   File "/home/bkc/temp/test.py", line 10, in ?
>     t()
>   File "/home/bkc/temp/test.py", line 4, in t
>     sys.exit(0)
> UnboundLocalError: local variable 'sys' referenced before assignment
> 
> This is not much of an error. The local import is superfluous, and no one
> would really write code this way. But should it raise an exception?

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.

-Peter



More information about the Python-list mailing list