Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #65062

Re: Why this throws an UnboundLocalError ?

From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: Why this throws an UnboundLocalError ?
Date 2014-01-30 17:56 -0500
References <CA+DCN_tQsZDckkueO7FiVYKihy2b9=SdeALJ4RwrQN_uk0dDLQ@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.6176.1391122593.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 1/30/14 5:46 PM, Marc Aymerich wrote:
> Dear all,
>
> I have a very simple module
>
> glic3@e4200:# cat globalstate.py
> GLOBAL = 0
>
> def update():
>      GLOBAL += 1
>
>
> however it doesn't work!!
>
> glic3@e4200:# python
> Python 2.7.3 (default, Aug  1 2012, 05:14:39)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import globalstate
>>>> globalstate.update()
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "globalstate.py", line 4, in update
>      GLOBAL += 1
> UnboundLocalError: local variable 'GLOBAL' referenced before assignment
>
>
> And I don't know why :(
> Anyone ?
>
> Thanks!!
>

Assignment statements in functions implicitly make local names. If you 
want to assign a new value to a global name in a function, you have to 
use a global statement:

def update():
     global GLOBAL
     GLOBAL += 1

-- 
Ned Batchelder, http://nedbatchelder.com

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Why this throws an UnboundLocalError ? Ned Batchelder <ned@nedbatchelder.com> - 2014-01-30 17:56 -0500

csiph-web