views:

36

answers:

2

Consider this:

>>> foo = {}
>>> foo[1] = 1.0
>>> foo[2] = foo[1]
>>> foo
{1: 0.0, 2: 0.0}
>>> foo[1] += 1.0
{1: 1.0, 2: 0.0}

This is what happens. However, what I want would be that the last line reads:

 {1: 1.0, 2: 1.0}

Meaning that both refer to the same value, even when that value changes. I know that the above works the way it does because numbers are immutable in Python. Is there any way easier than creating a custom class to store the value?

+1  A: 

The easier way to have a kind of pointer in python is pack you value in a list.

>>> foo = {}
>>> foo[1] = [1.0]
>>> foo[2] = foo[1]

>>> foo
{1: [1.0], 2: [1.0]}

>>> foo[1][0]+=100 # note the [0] to write in the list

>>> foo
{1: [101.0], 2: [101.0]}

Works !

mb14
+1  A: 

It is possible only with mutable objects, so you have to wrap your immutable value with some mutable object. In fact any mutable object will do, for example built-in list:

>>> n = [0]
>>> d = { 1 : n, 2 : n }
>>> d
{1: [0], 2: [0]}
>>> d[1][0] = 3
>>> d
{1: [3], 2: [3]}

but what's hard in creating your own class or object?

>>> n = type( "number", ( object, ), { "val" : 0, "__repr__" : lambda self: str(self.val) } )()
>>> d = { 1 : n, 2 : n }
>>> d
{1: 0, 2: 0}
>>> d[1].val = 9
>>> d
{1: 9, 2: 9}

Works just as fine ;)

cji