David Callanan
David Callanan

Reputation: 5958

Python reassign value instead of variable

Is it possible to reassign the value referenced to by a variable, rather than the variable itself?

a = {"example": "foo"}
b = a

When I reassign a, it is reassigning the variable a to reference a new value. Therefore, b does not point to the new value.

a = {"example": "bar"}
print(b["example"]) # -> "foo"

How do I instead reassign the value referenced by a? Something like:

*a = {"example": "bar"}
print(b["example"]) # -> "bar"

I can understand if this isn't possible, as Python would need a double pointer under the hood.


EDIT Most importantly, I need this for reassigning an object value, similar to JavaScript's Object.assign function. I assume Python will have double pointers for objects. I can wrap other values in an object if necessary.

Upvotes: 0

Views: 935

Answers (2)

Thomas Weller
Thomas Weller

Reputation: 59228

You are creating 2 dictionaries, so that's 2 different objects in memory. If you don't want that, keep 1 dictionary only.

a = {"example": "foo"}
b = a
a["example"] = "bar"
print(b["example"])

Upvotes: 1

chepner
chepner

Reputation: 530920

Python variables simply do not operate this way, and simple assignment won't do what you want. Instead, you can clear the existing dict and update it in-place.

>>> a = dict(example="foo")
>>> b = a
>>> a.clear()
>>> a
{}
>>> a.update({'example': 'bar'})
>>> b
{'example': 'bar'}

Upvotes: 2

Related Questions