Trouble accessing global vars

Troels Therkelsen t_therkelsen at hotmail.com
Sat Sep 4 18:17:02 CEST 2004


In article <sonjj0d6b7fsafjnphqcdqrm0ia59qt8ti at 4ax.com>, Fernando Rodríguez wrote:
> Hi,
> 
> I haven't used Python in quite some time, and I'm bit puzzled by this:
> 
> counter = 0
> 
> class Blah(object):
> 	def run(self):
> 		counter += 1
> 
> b = Blah()
> b.run()
> 
> Traceback (most recent call last):
>   File "<pyshell#53>", line 1, in -toplevel-
>     b.run()
>   File "<pyshell#51>", line 3, in run
>     counter += 1
> UnboundLocalError: local variable 'counter' referenced before assignment
> 
> However, counter is not a local var, it's a global one. :-? Shouldn't this
> work?

If you want to modify a global variable from inside a function/method scope,
you need explicitly tell Python that this is indeed your wish, by using the
global keyword, like this:

    class Blah(object):
        def run(self):
            global counter
            counter += 1

Hope this helps,

Troels Therkelsen




More information about the Python-list mailing list