tracking variable value changes

Ian Kelly ian.g.kelly at gmail.com
Thu Dec 8 16:50:38 EST 2011


On Thu, Dec 8, 2011 at 1:17 PM, Catherine Moroney
<Catherine.M.Moroney at jpl.nasa.gov> wrote:
> Hello,
>
> Is there a way to create a C-style pointer in (pure) Python so the following
> code will reflect the changes to the variable "a" in the
> dictionary "x"?
>
> For example:
>
>>>> a = 1.0
>>>> b = 2.0
>>>> x = {"a":a, "b":b}
>>>> x
> {'a': 1.0, 'b': 2.0}
>>>> a = 100.0
>>>> x
> {'a': 1.0, 'b': 2.0}   ## at this point, I would like the value
>                       ## associated with the "a" key to be 100.0
>                       ## rather than 1.0
>
> If I make "a" and "b" numpy arrays, then changes that I make to the values
> of a and b show up in the dictionary x.
>
> My understanding is that when I redefine the value of "a", that Python
> is creating a brand-new float with the value of 100.0, whereas when I use
> numpy arrays I am merely assigning a new value to the same object.

Sort of.  In the code above, you are binding a and x["a"] to the same
float object.  Then when you do "a = 100.0", you are rebinding a but
not x["a"].  In the case of arrays it's the same story, except that
you can also *modify* the contents of the array instead of rebinding
to a new array.  In that case both a and x["a"] are still bound to the
original array, the contents of which have changed.

You can get the same effect with a float by putting it in a container
object and binding both variables to the same container objects rather
than to the float directly.  Then, to change the value, change the
contents of the container object.  What you use as a container object
is up to you.  Some use a 1-element list, although I find that ugly.



More information about the Python-list mailing list