Modifying the value of a float-like object

Christian Heimes lists at cheimes.de
Tue Apr 14 11:52:01 EDT 2009


Eric.Le.Bigot at spectro.jussieu.fr wrote:
> Hello,
> 
> Is there a way to easily build an object that behaves exactly like a
> float, but whose value can be changed?  The goal is to maintain a list
> [x, y,…] of these float-like objects, and to modify their value on the
> fly (with something like x.value = 3.14) so that any expression like "x
> +y" uses the new value.


Your approach doesn't follow the Python philosophy thus it's most likely
to fail. It is possible to implement a mutable float like object --
Python doesn't stop you from shooting yourself in the knee -- but please
don't harm yourself.

Python has an easy way to archive an equal goal:

data = [1.0, 2.0, -1.0, -7.0, 23.0]
for idx, value in enumerate(data):
    if value < 0.0:
        data[idx] = value**2

Important side note:
It's ok to modify elements of a list while iterating over the same list.
But you should not remove, append, insert or reorder the list while you
are iterating over it. It will lead to surprising effects.

Christian



More information about the Python-list mailing list