0

I understand that in python, variables are not storage locations but instead just a name that points to a value elsewhere. Therefore we cannot do something like:

foo = 1
bar = foo
foo = 2

and expect bar to be updated to 2.

However I am wondering if we can store the "name" foo in a dict and update where the name points to. I know the following does not work but something along the lines of:

foo = 1
bar = 2
dict_of_var = {
  "foo": foo,
  "bar": bar,
  "baz": baz
}
with open(path, 'r') as f:
  f_dict = json.load(f)
for key, val in dict_of_var.items():
  val = f_dict[key]

Instead of the manual:

with open(path, 'r') as f:
  f_dict = json.load(f)
foo = f_dict["foo"]
bar = f_dict["bar"]
baz = f_dict["baz"]

Is this possible at all, either in this way or some other way?

ljden
  • 352
  • 1
  • 11

3 Answers3

0

It's not what I was after but a "workaround" could be to instead store a setter method to update the variable. This is not any more elegant than just manually assigning the variables but does technically work

foo = 1
bar = 2
def set_foo(val):
  global foo
  foo = val

def set_bar(val):
  global bar
  bar = val

dict_of_var = {
  "foo": set_foo,
  "bar": set_bar
}
with open(path, 'r') as f:
  f_dict = json.load(f)
for key, val in f_dict.items():
  dict_of_var[key](val)
ljden
  • 352
  • 1
  • 11
0

You can use the built-in functions globals() and locals() to achieve that.

>>> foo = 1
>>> foo
1
>>> g = globals()
>>> g["foo"] = 3
>>> foo
3

Modifying locals() is a bad idea though. Modifying globals() is probably okay (since it always points to the same dict) but since it deals with global variables it's also a bad idea.

I feel like this is an XY case but without the exact use cases this is the only answer I can offer.

  • Yeah a namespace was looking like a somewhat suitable candidate. I've decided to not bother but I put a simplified example of what I was attempting in my answer if you're curious – ljden Apr 01 '22 at 03:33
0

You can try this:

a = [10]

dict1 = { "A" : a}

dict1["A"][0] = 11

print(a) -> [11]

Maybe this is what you was looking for.

Skobo Do
  • 49
  • 6