Trouble accessing global vars

Lenard Lindstrom len-1 at telus.net
Sat Sep 4 13:11:53 EDT 2004


Fernando Rodríguez <fernandoSPAM.YOURSELF at fernando-rodriguez.com> writes:

> 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?

Name counter has to be declared global in method run:

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

The augmented assignment statements such as counter += 1 bind a name to
a value. Binding a name within a function block makes the variable local
by default.

Lenard Lindstrom
<len-l at telus.net>



More information about the Python-list mailing list