Walt Mankowski on 4 Oct 2004 15:00:03 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] python and global name space


On Mon, Oct 04, 2004 at 10:35:34AM -0400, Jeff Abrahamson wrote:
> In a python program I want to have a global counter that's available
> from different functions.
> 
> I'm not getting it right and reading the manual hasn't helped yet.
> Anyone know what it is I want to do?
> 
> In the snippet below, I'm hoping foo() will side-effect the global
> num.  It doesn't.
> 
> Thanks much for any suggestions.
> 
>     jeff@asterix:AI-hw $ python
>     Python 2.3.4 (#2, Jul  5 2004, 09:15:05)
>     [GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2
>     Type "help", "copyright", "credits" or "license" for more information.
>     >>> global num
>     >>> num = 0
>     >>> def foo():
>     ...     num += 5
>     ...     print num
>     ...
>     >>> num
>     0
>     >>> foo()
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>       File "<stdin>", line 2, in foo
>     UnboundLocalError: local variable 'num' referenced before assignment
>     >>>

You have to declare num as global in the *function*, not in the outer
scope.  So this works:

num = 1
print num

def foo():
    global num
    num += 5
    print num

foo()

print num

I can't find a good explanation of why exactly this works in the
online tutorial, and my python's a bit rusty.  Python's scoping rules
are strange, but I don't remember exactly *how* they're strange.  I'll
try to check my python books when I get home tonight.

Walt

Attachment: signature.asc
Description: Digital signature