Fun with locals and globals
I wanted to know how to use functions and variables where I only get the name as a string.
It isn't like e. g. in PHP that you can put another $
infront of the variable, since variables do not start with a special sign.
One has to get to know locals
and the globals
functions.
Add variables where you have the name as a string and their initial values.
Since I know of nothing like the PHPs
$foo = 'bar';
$$foo = 3;
echo $bar;
One has to write directly into the globals dictionary which is not a function that contains a dictionary (o.O?)
>>> foo = 'bar'
>>> globals()[foo] = 3
>>> print(bar)
3
. Or another case:
for i in ["a", "b", "c"]:
globals()[i] = 1337
Reading
Also if one wants to call a function for which one only has got the name as a string like in PHP
$foo="foo"; $$foo()
In Python one has to use the locals
or globals
functions as far as I know:
>>> def foo():
... print("foo")
>>>
>>> locals()["foo"]()
"foo"
and inside a function:
>>> def bar():
... globals()["foo"]()
General remarks
>>> def a():
... global c
... c = 3
>>> a()
>>> print(c)
3
>>> del c