function with a state

Andrew Koenig ark at
Sun Mar 6 16:25:11 CET 2005

"Xah Lee" <xah at> wrote in message 
news:1110096425.669042.11050 at

> globe=0;
> def myFun():
>  globe=globe+1
>  return globe
> apparently it can't be done like that. I thought it can probably be
> done by prefixing the variable with some package context...

You can do this:

    def myFun():
        global globe
        return globe

The question you should ask yourself, however, is why you want to do this. 
Do you really want to tie your function to a single global variable?  Are 
you sure you will never need more than one?

For example, the function you've written represents a counter.  Are you sure 
you will never need more than one such counter?

More information about the Python-list mailing list