Jeff Abrahamson on 4 Oct 2004 14:36:02 -0000


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

[PLUG] python and global name space


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

-- 
 Jeff

 Jeff Abrahamson  <http://www.purple.com/jeff/>    +1 215/837-2287
 GPG fingerprint: 1A1A BA95 D082 A558 A276  63C6 16BF 8C4C 0D1D AE4B

 A cool book of games, highly worth checking out:
 http://www.amazon.com/exec/obidos/ASIN/1931686963/purple-20

Attachment: signature.asc
Description: Digital signature