static statements and thread safety

Chris Angelico rosuav at gmail.com
Thu Sep 22 04:06:45 EDT 2011


On Thu, Sep 22, 2011 at 5:45 PM, Eric Snow <ericsnowcurrently at gmail.com> 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}):
    statics['sum']+=n
    return statics['sum']

>>> accumulate(1)
1
>>> accumulate(10)
11
>>> accumulate(20)
31
>>> accumulate(14)
45

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
    sum+=n
    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.

ChrisA



More information about the Python-list mailing list