0

I understand why below works as such:

v = 1
d = dict()
d['hi'] = v
d['hi'] = 2
print(v)  # prints 1 as expected

And also why this works:

class Node:
  def __init__(self,val):
    self.val = val


n = Node(1)
d['hi_node'] = n
d['hi_node'].val = 100
print(n.val)  # prints 100 as expected

I also believe that I understand why the below works as such:

n2 = Node(2)
d['hi_n2'] = n2
n3 = Node(3)
val_in_d = d['hi_n2']  # creates a new binding of name val_in_d
val_in_d = Node(3) # updates the location to which val_in_d points
print(n2.val) # still 2

But is there any way to point n2 to n3 using dictionary d which has the similar impact as writing n2 = n3? So, finally if I print n2.val, I get 3 i.e. I wish to take the value stored in the dictionary and change it's reference to point to another object rather than just updating the value that is stored in dictionary.

Any help would be highly appreciated.

Vimanyu
  • 625
  • 2
  • 9
  • 24

1 Answers1

0

The issue is you didn't change the value of the pointer, you changed the pointer itself.

n2 = Node(2)
d['hi_n2'] = n2
n3 = Node(3)
val_in_d = d['hi_n2']  # Here you get the pointer that points at n2
val_in_d = Node(3) # By assigning val_in_d to the Node constructor result you change the pointer
print(n2.val) # still 2

Instead you have to use the actual value such as:

n2 = Node(2)
d['hi_n2'] = n2
n3 = Node(3)
val_in_d = d['hi_n2'] # Get pointer
val_in_d.val = 3 # Change value in the object,
print(n2.val) # Prints 3

Alternatively you could create a middle man class / wrapper to prevent python from changing the desired pointer such as Python variable reference assignment.

  • @error-syntactical-remorse: Thanks for your solution. I believe that creating a middle man class/wrapper would be the way to go for my case. In my contrived example here, it was easy to simply change just the `val` to 3 but in my actual scenario, n2 would be either be `None` or if it is an instance of the `Node` then after the assignment `id(n2)` should be equal to `id(n3)` i.e. it should point to n3 rather than just changing the value. – Vimanyu May 09 '19 at 15:35