static statements and thread safety

Chris Angelico rosuav at
Thu Sep 22 10:06:45 CEST 2011

On Thu, Sep 22, 2011 at 5:45 PM, Eric Snow <ericsnowcurrently at> wrote:
> I would expect that static variables would work pretty much the same
> way as default arguments

Could you just abuse default arguments to accomplish this?

def accumulate(n,statics={'sum':0}):
    return statics['sum']

>>> accumulate(1)
>>> accumulate(10)
>>> accumulate(20)
>>> accumulate(14)

This eliminates any sort of "end of function write-back" by writing to
static storage immediately. Of course, syntactic assistance would make
this look cleaner, for instance:

def accumulate(n):
    static sum=0
    return sum

Both of these would, of course, have thread-safety issues. But these
can be resolved by figuring out exactly what you're trying to
accomplish with your static data, and what it really means when two
threads are affecting it at once.


More information about the Python-list mailing list