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?
CodePudding user response:
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.
CodePudding user response:
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)
CodePudding user response:
Python doesn't really use pointers. More or less everything in python is built using dictionaries and arrays.
Therefore, you would usually keep all of your variables inside the dictionary, or move it to another variable in some way using logic or a loop.
There is also an easier way to address dictionaries. This tutorial is a good place to start learning the basics.
Here's an interesting article regarding pointers in python. The main reason they don't exist is that python isn't anywhere near as low level as C or C .
some_dict = {"foo": "a value", "bar": "another value"}
print(some_dict["foo"])
# a value
# in the case of what you're trying to achieve, you would keep
# it in a dictionary as the values are where they already need
# to be (remember, python doesn't have any memory management)
# should you really want to set the variables you could use this
# very inefficient method
foo: str # this really does nothing since it's python xd
bar: str
for key in some_dict:
if key == "foo":
foo = some_dict[key]
elif key == "bar"
bar = some_dict[key]