Why this throws an UnboundLocalError ?

Chris Angelico rosuav at gmail.com
Thu Jan 30 17:53:18 EST 2014


On Fri, Jan 31, 2014 at 9:46 AM, Marc Aymerich <glicerinu at gmail.com> wrote:
> GLOBAL = 0
>
> def update():
>     GLOBAL += 1

If you assign to a name, Python makes it local, unless you explicitly
tell it that you want it to be global:

def update():
    global GLOBAL
    GLOBAL += 1

But be aware that the ALL_CAPS name conventionally means a constant.
Since you're changing its value, it's not constant (wow! :) ), so
using a name of GLOBAL is a bad idea. (Also, obviously, you want to
name it appropriately to what you're doing, but I assume you called it
this as part of cutting down your example. For which, by the way,
thank you. You posted a complete example, and the full traceback, and
the Python version and platform. That's everything that we need to
help you - it's such a luxury!!)

ChrisA



More information about the Python-list mailing list