[Tutor] Referencing global variables

Jeff Shannon jeff@ccvcorp.com
Wed, 04 Sep 2002 13:51:43 -0700


Jon Cosby wrote:

>  Why does this not work: >>> count = 0
> >>> def increment(n):
> ...     for i in range(n):
> ...             count = count + 1
> ...     return count
> ...
> >>> increment(5)
> UnboundLocalError: local variable 'count' referenced before
> assignment "count" is global, isn't it?

Actually, it's not.

Well, technically, there's a global count *and* a local count.
Assignment to a variable, within the scope of a function, creates a
local variable regardless of the existence of a similarly-named
global.  Since locals are determined at compile-time (when the
interpreter loads the function) rather than run-time, any usage of
'count' within the function applies to the local variable, even
*before* that local has been assigned to.  Thus, 'count = count + 1'
tries to access the value of the local 'count', add one to it, and
then assign the results back to (the local version of) 'count'.  The
first time this happens, there *is* no value for the local 'count',
thus the exception you see.

The simple solution, as Sean pointed out, is to declare that 'count'
is a global before you use it in the function.  This will get exactly
the behavior you're expecting.  The not-so-simple solution would be to
find some other way of counting whatever it is that you're counting,
but doing that would require more knowledge of what you're trying to
do.  ;)  In particular, I wonder why you're not using this:

def increment(n):
    global count
    return count + n

which seems much more sensible than the for-loop that you're using,
but perhaps there's some reason in the details that you've left out.
(For that matter, I wonder why you wouldn't use 'count += n' instead
of 'increment(n)' ... but I suppose you probably have a reason that
wasn't germane to the specific problem you're asking about.)

Jeff Shannon
Technician/Programmer
Credit International