UnboundLocalError on shadowed import

Brad Clements bkc at Murkworks.com
Tue Jun 29 14:18:25 EDT 2004


I was going to file this as a bug in the tracker, but maybe it's not really
a bug. Poor Python code does what I consider to be unexpected. What's your
opinion?

With Python 2.3.2 (but also happens with 2.2)

An import within a function that shadows a global import can raise
UnboundLocalError. I think the real problem is that the the local 'import
sys' is seen as occuring after the use of sys within this function, even
though sys is imported in global scope.

import sys

def t():
    sys.exit(0)
    import sys
    sys.exit(1)

if __name__ == "__main__":
    t()

I noticed this when editing an existing module. After adding 'import sys' at
the global level and then using sys in the function (and not noticing that
this function imported sys locally below), I got the UnboundLocalError

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?



-- 
Novell DeveloperNet Sysop #5

_







More information about the Python-list mailing list