static statements and thread safety

Eric Snow ericsnowcurrently at gmail.com
Thu Sep 22 04:16:11 EDT 2011


On Thu, Sep 22, 2011 at 2:06 AM, Chris Angelico <rosuav at gmail.com> wrote:
> 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.

That's a good point.  So, isn't the default arguments hack in the same
boat with regards to threads?

Maybe I'm just misunderstanding the thread concept in Python.  Threads
have separate execution stacks but share interpreter global state,
right?

-eric

>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list