I need to assign some variables when calling a funcion with the name of the variable as an argument.
Therefore, I loop through a tuple with the desired names, assigning them via the locals() dict.
It works, but then I can't access them by name - even inside the function itself.
def function():
    var_names = ("foo","bar","foobar")
    for var_name in var_names:
        locals()[var_name] = len(var_name)
    print foo
Throws:
Traceback (most recent call last):
  File "error_test.py", line 8, in <module>
    function()
  File "error_test.py", line 5, in function
    print foo
NameError: global name 'foo' is not defined
With the following code it works well:
def function():
    var_names = ("foo","bar","foobar")
    for var_name in var_names:
        locals()[var_name] = len(var_name)
    print locals()["foo"]
Isn't it that the locals() dict contains just the normal function variables? Why isn't it working?
 
     
     
     
    