Declare a variable global

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Feb 19 16:46:40 EST 2007


yinglcs at gmail.com a écrit :
> 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:
> #!/usr/bin/python
> 
> import re
> import sys
> import time
> import os
> import shutil
> 
> colors = ["#FF0000",  "#00FF00", "#0000FF",
> "#FFFF00" ,"#FFA500" ,"#DA70D6"]
> colorIndex = 0
> 
> def getText( intputstr):
>     rc = ""
> 
>     maxX = 0;
>     maxY = 0;
>     minX = 10000000;
>     minY = 10000000;
> 
> 
>     for str in intputstr:

don't use str as an indentifier unless it's ok for you to shadow the 
builtin type str.

>         print str;
> 
>         if str != "":
           if str:
>             pattern = "x:(\d+) y:(\d+) w:(\d+) h:(\d+) (.*)" 
>             match = re.findall(pattern, str)

Move loop invariants (here, your pattern) outside of the loop. And while 
you're at it, compile it.

>             if match:
>                 x, y, width, height, area = match[0]
> 
>                 colorIndex = colorIndex + 1

You're not reading colorIndex, you're rebinding it. In this case, you do 
need to declare it global (or better, to rethink your code to avoid 
globals).

>                 rc = rc + "<rect x=\"%(x)s\" y=\"%(y)s\" width=\"%
> (width)s\" height=\"%(height)s\" " % locals()

Using augmented assignment (ie : +=) may be more readable here (MHO).
Also, if you use single quotes for the template string, you can save the 
escapes:
                   rc += '<rect x="%(x)s" y="%(y)s" width="%
  (width)s " height="%(height)s' " % locals()

And FWIW, you might want to define the template string outside the loop.

>                 rc = rc + "fill=\"%s\" stroke=\"#000000\" stroke-width=
> \"1px\" fill-opacity=\".5\" />\n"  % colors[colorIndex  % len(colors)]

idem

(snip)





More information about the Python-list mailing list