0

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.

10
  • 1
    you will find this useful: nedbatchelder.com/text/names1.html Jan 22, 2020 at 21:06
  • 2
    You could use a box type or a container (e.g. list) to hold an indirect reference. Jan 22, 2020 at 21:09
  • 2
    for a dictionary, just clear it, and update it with new data: you keep the old reference. For a list, use a[:] = ... to keep the old reference. Jan 22, 2020 at 21:11
  • 2
    Was this a case of the XY problem, in the end?
    – AMC
    Jan 22, 2020 at 21:19
  • 3
    @Sayse python had no distinction between value types and reference types. Everything acts like a reference type, everything is an object. And mutability isn't relevant here, really, both immutable and mutable types behave the exact same way as far as assignment works Jan 22, 2020 at 21:32

2 Answers 2

2

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'}
1
  • That's exactly it, thanks! update is the method I was looking for. Jan 22, 2020 at 21:14
1

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"])
1
  • However, I am given another dict from another function, and need to transfer that into my existing dictionary. update is what I was looking for in @chepner's answer Jan 22, 2020 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.