Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #16881

Re: tracking variable value changes

References <jbr607$eer$1@news.jpl.nasa.gov>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-12-08 14:50 -0700
Subject Re: tracking variable value changes
Newsgroups comp.lang.python
Message-ID <mailman.3456.1323381077.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Dec 8, 2011 at 1:17 PM, Catherine Moroney
<Catherine.M.Moroney@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.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

tracking variable value changes Catherine Moroney <Catherine.M.Moroney@jpl.nasa.gov> - 2011-12-08 12:17 -0800
  Re: tracking variable value changes Ian Kelly <ian.g.kelly@gmail.com> - 2011-12-08 14:50 -0700
  Re: tracking variable value changes Ben Finney <ben+python@benfinney.id.au> - 2011-12-09 09:06 +1100
  Re: tracking variable value changes Arnaud Delobelle <arnodel@gmail.com> - 2011-12-08 22:10 +0000
  Re: tracking variable value changes Andrea Crotti <andrea.crotti.0@gmail.com> - 2011-12-09 12:43 +0000
    Re: tracking variable value changes alex23 <wuwei23@gmail.com> - 2011-12-11 21:45 -0800
  Re: tracking variable value changes Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-12-10 00:41 +0000

csiph-web