How to address a global variable in a function

Chris Rebert clp2 at rebertia.com
Sat Aug 8 00:14:58 EDT 2009


On Fri, Aug 7, 2009 at 11:29 PM, n179911<n179911 at gmail.com> wrote:
> HI,
>
> I have a global variable
>
> // line 8
> tx  = 0
>
> and then I have this function (start in line 12):
> def handleTranslate(result):
>        print line
>        txStr, tyStr = result.group(1), result.group(2)
>        print txStr, tyStr
>
>        tx += int(txStr)
>        ty += int(tyStr)
>
>        return
>
> But I am getting this error:
>    handleTranslate(result)
>  File "buildsvg.py", line 22, in handleTranslate
>    tx += int(txStr)
> UnboundLocalError: local variable 'tx' referenced before assignment
>
> How can I fix it?
> I have assigned 'tx' to 0 in line 8. I don't understand why i get this
> error.

By default, Python assumes that any variables assigned to in a
function are local variables. To change this assumption, you need to
declare that you want to reference a global variable. This is done by
putting a `global` statement at the start of the function (i.e.
`global tx`).

In the future, you might STFW (in this case, for "UnboundLocalError")
before posting to the newsgroup, as you would have found several
explanations of this common newbie-biter.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list