Modifying the value of a float-like object

Steven D'Aprano steve at
Wed Apr 15 16:07:58 CEST 2009

On Wed, 15 Apr 2009 05:59:39 -0400, Dave Angel wrote:

> Steven D'Aprano wrote:
>> On Tue, 14 Apr 2009 14:45:47 -0400, Dave Angel wrote:
>>> The answer to your original question is no.  If the value can be
>>> changed, then it doesn't behave like a float.  And that's not just a
>>> pedantic answer, it's a serious consideration.
>> Oh nonsense. Many programming languages have mutable floats.
> That's irrelevant.  Python doesn't.  So introducing one will quite
> likely alter the OP's code's behavior.  It doesn't matter if it's
> possible, it matters whether the existing code's behavior might change,
> and of course if a future maintainer might have trouble making sense of
> it.

What are you talking about? Python introduces new types quite frequently. 
We now have sets, frozensets, rationals, decimals and namedtuples, and 
we'll soon be getting ordereddicts and probably others as well. People 
create new types in their code *all the time*, using the class statement. 
If the OP wants to create a MutableFloat type, that's his prerogative.

> BTW, just what languages have mutable floats?

C and Pascal. Probably Java. As far as I know, any language with 
variables. Here's a sample piece of Pascal code which demonstrates that 
assignment to a float mutates the value in a fixed memory location:

program main(input, output);
    x: real;  {called 'float' in other languages}
    ptr: ^real;

  x := 23.0;
  ptr := @x;  {point ptr to the location of x}
  writeln('Before: x = ', x, '; address = ', integer(ptr));
  x := 42.0;
  ptr := @x;
  writeln('After: x = ', x, '; address = ', integer(ptr));

Executing it, I get:

Before: x =  2.300000000000000e+01; address = 134692368
After: x =  4.200000000000000e+01; address = 134692368

The equivalent in Python is this:

>>> x = 23.0
>>> print 'Before: x = ', x, '; address = ', id(x)
Before: x =  23.0 ; address =  147599964
>>> x = 42.0
>>> print 'After: x = ', x, '; address = ', id(x)
After: x =  42.0 ; address =  147599980

As you can see, x becomes bound to a completely different float object.

> I don't think I've come
> across any since Fortran (on a CDC 6400), and I don't think that was
> deliberate.  In that implementation it was possible to change the value
> of a literal 2.0 to something else.

Who is talking about changing the values of float literals? That would be 
very silly.

> If you're going to use the fact that many languages pass arguments by
> reference, 

Nobody is talking about parameter passing conventions.


More information about the Python-list mailing list