tracking variable value changes

Andrea Crotti andrea.crotti.0 at gmail.com
Fri Dec 9 07:43:07 EST 2011


On 12/08/2011 08:17 PM, Catherine Moroney 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.
>
> Is there some way to rewrite the code above so the change of "a" from
> 1.0 to 100.0 is reflected in the dictionary.  I would like to use
> simple datatypes such as floats, rather than numpy arrays or classes.
> I tried using weakref's, but got the error that a weak reference cannot
> be created to a float.
>
> Catherine

Not sure if it's exactly pure python but Traits can actually do this
https://github.com/enthought/traits



More information about the Python-list mailing list