Declare a variable global
Steve Holden
steve at holdenweb.com
Mon Feb 19 16:43:58 EST 2007
yinglcs at gmail.com wrote:
> On Feb 19, 11:09 am, Jean-Paul Calderone <exar... at divmod.com> wrote:
>> On 19 Feb 2007 09:04:19 -0800, "ying... at gmail.com" <ying... at gmail.com> wrote:
>>
>>> Hi,
>>> I have the following code:
>>> colorIndex = 0;
>>> def test():
>>> print colorIndex;
>>> This won't work.
>> Are you sure?
>>
>> exarkun at charm:~$ cat foo.py
>> colorIndex = 0
>>
>> def test():
>> print colorIndex
>>
>> test()
>> exarkun at charm:~$ python foo.py
>> 0
>> exarkun at charm:~$
>>
>> 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
More information about the Python-list
mailing list