function with a state

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sun Mar 6 15:54:23 CET 2005


Xah Lee wrote:
> is it possible in Python to create a function that maintains a variable
> value?
> 
> something like this:
> 
> globe=0;
> def myFun():
>   globe=globe+1
>   return globe

You could work with function attributes:


def myFun():
    try:    myFun.globe += 1
    except: myFun.globe = 1

    return myFun.globe

or with a default function argument:


class Dummy: pass

def myFun(globe=Dummy()):
    try:    globe.globe += 1
    except: globe.globe = 1

    return globe.globe

Reinhold



More information about the Python-list mailing list