Curious UnboundLocalError Behavior

Matthew Franz mdfranz at gmail.com
Wed Feb 28 12:15:13 EST 2007


I'm probably fundamentally misunderstanding the way the interpreter
works with regard to scope, but is this the intended behavior...

franz-macbook:~ mdfranz$ python unboundlocal.py
('Darwin', 'franz-macbook.local', '8.8.5', 'Darwin Kernel Version
8.8.5: Mon Dec 11 19:39:17 PST 2006;
root:xnu-792.16.5.obj~1/RELEASE_I386', 'i386')
2.4.3 (#1, Feb 24 2007, 23:01:32)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]
{'__builtins__': <module '__builtin__' (built-in)>, '__file__':
'unboundlocal.py', 'SOMEGLOBAL': 1, 'sys': <module 'sys' (built-in)>,
'__name__': '__main__', 'foo': <function foo at 0x42cf0>, 'os':
<module 'os' from
'/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.pyc'>,
'__doc__': None}
SOMEGLOBAL:
Traceback (most recent call last):
  File "unboundlocal.py", line 15, in ?
    foo()
  File "unboundlocal.py", line 11, in foo
    print "SOMEGLOBAL:",SOMEGLOBAL
UnboundLocalError: local variable 'SOMEGLOBAL' referenced before assignment


Where unboundlocal.py is...

import os,sys

SOMEGLOBAL=1

def foo():
    dome=False
    if dome:
        SOMEGLOBAL = 0

    print globals()
    print "SOMEGLOBAL:",SOMEGLOBAL

print os.uname()
print sys.version
foo()

Is SOMEGLOBAL is some weird in-between state, since it is referenced
within foo() but not actually assigned?

If I set dome to True SOMEGLOBAL gets overriden (as I would have expected)

franz-macbook:~ mdfranz$ python unboundlocal.py
('Darwin', 'franz-macbook.local', '8.8.5', 'Darwin Kernel Version
8.8.5: Mon Dec 11 19:39:17 PST 2006;
root:xnu-792.16.5.obj~1/RELEASE_I386', 'i386')
2.4.3 (#1, Feb 24 2007, 23:01:32)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]
{'__builtins__': <module '__builtin__' (built-in)>, '__file__':
'unboundlocal.py', 'SOMEGLOBAL': 1, 'sys': <module 'sys' (built-in)>,
'__name__': '__main__', 'foo': <function foo at 0x42cf0>, 'os':
<module 'os' from
'/opt/local/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.pyc'>,
'__doc__': None}
SOMEGLOBAL: 0



-- 
Matthew Franz
http://www.threatmind.net/



More information about the Python-list mailing list