[EMAIL PROTECTED] wrote: > On Feb 19, 11:09 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: >> On 19 Feb 2007 09:04:19 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: >> >>> Hi, >>> I have the following code: >>> colorIndex = 0; >>> def test(): >>> print colorIndex; >>> This won't work. >> Are you sure? >> >> [EMAIL PROTECTED]:~$ cat foo.py >> colorIndex = 0 >> >> def test(): >> print colorIndex >> >> test() >> [EMAIL PROTECTED]:~$ python foo.py >> 0 >> [EMAIL PROTECTED]:~$ >> >> The global keyword lets you rebind a variable from the module scope. It >> doesn't have much to do with accessing the current value of a variable. >> >> Jean-Paul > > Thanks. Then I don't understand why I get this error in line 98: > > Traceback (most recent call last): > File "./gensvg.py", line 109, in ? > outdata, minX, minY, maxX, maxY = getText(data); > File "./gensvg.py", line 98, in getText > print colorIndex; > UnboundLocalError: local variable 'colorIndex' referenced before > assignment > > > Here is my complete script: [... script elided ...]
Well, now I've seen the error message I don't even need to see the script to explain what's going on. Unfortunately in your (entirely creditable) attempt to produce the shortest possible script that showed the error you presented a script that *didn't* have the error. Python determines whether names inside a function body are local to the function or global to the module by analyzing the function source. If there are bindings (assignments) to the name inside the body then the name is assumed to be local to the function unless a global statement declares otherwise. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 -- http://mail.python.org/mailman/listinfo/python-list