floatref

Roald de Vries downaold at gmail.com
Wed Jul 14 04:11:54 EDT 2010


On Jul 14, 2010, at 3:53 AM, Steven D'Aprano wrote:
> On Tue, 13 Jul 2010 19:26:34 +0200, Roald de Vries wrote:
>
>> Hi all,
>>
>> I have two objects that should both be able to alter a shared  
>> float. So
>> i need something like a mutable float object, or a float reference
>> object. Does anybody know if something like that exists? I know  
>> it's not
>> hard to build, but I have a feeling that there should be a standard
>> solution to it.
>
>
> One standard solution would be to wrap the float in a class as an
> attribute.

E.g.: a class FloatWrapper with a get and set method.
Advantages: transparent, easy to implement
Disadvantages: for 'f = FloatWrapper' you have to use 'f.set(1.0)'  
instead of 'f = 1.0', which reads less easily (I think), and a mistake  
like assigning with 'f = 1.0' is easily made.

> Another is to put it in a list:
>
> myvalue = [3.1415]
> pi = myvalue
> myvalue[0] = 3.0
> assert pi[0] == 3.0

I thought about something like that, but it's a bit misleading,  
because the value is actually a list.

> An even better solution is to avoid the idiom of shared state in the
> first place. Whenever people say "I need shared data", the chances are
> very good that they don't *need* it at all, but merely *want* it  
> because
> that's the idiom they're used to.

I want to simulate a distributed algorithm, in which components can  
only communicate through shared state.

Cheers, Roald



More information about the Python-list mailing list