[sclug] Python global variable question

Pieter Claassen pieter at claassen.co.uk
Thu Nov 26 13:41:43 UTC 2009

Hi Andrew,

Sorry, I am daft. Here is a solution I found on the web


def static_num(self):
       c = 0
       while True:
            c = c + 1
            yield c

You get the new increment by calling self.count()

The state and counter logic is completely stored in the closure so no risk
of global interference.

When is java going to get first class functions? Things are too easy as they


On Thu, Nov 26, 2009 at 11:50 AM, Andrew Nelis <andrew.nelis at gmail.com>wrote:

> 2009/11/26 pieter claassen <pieter at claassen.co.uk>:
> > I am trying *not* to store a counter in a global variable in Python. Does
> > anybody have a suggestion for how to do this elegantly?
> There might be some way within your source to do it more elegantly but
> I think the general solution is to hide it within a pair of functions;
> __the_counter = 0
> def getCounter():
>    return __the_counter
> def incrementCounter( amount=1 ):
>    global __the_counter
>    __the_counter += amount
>    return __the_counter
> Then use the functions rather than the variable.
> Cheers,
> Andy.

Pieter Claassen

More information about the Sclug mailing list