September 3rd, 2004, 11:22 AM
Modifying Local Variables via a dict
I need something similiar to the following:
Unfortunately, modifying the dict returned by locals() is discouraged because "changes may not affect the values of local variables used by the interpreter." It is reliable in all the cases I have tried it, however, I don't want to disregard the warning.
>>> l = locals()
>>> l['foo'] = 'bar'
So, I consider doing the following instead:
From what little documentation on f_locals I have seen, it appears that it returns a reference to the local dict, and hence should be safe to modify in this way. Is this an accurate conclusion? If not, what would work? Also, is there any more documentation available on the frameobject besides what is in the python reference?
>>> import sys
>>> sys._getframe().f_locals['foo'] = 'bar'
September 3rd, 2004, 06:23 PM
This seems like a question for Python's implementors
What is it you are trying to achieve, are you sure you need to do this?
September 4th, 2004, 03:22 AM
assigning to locals() works at the global scope, but will fail inside a function since it returns a copy of the dictionary. I don't know enough about f_locals to know if it will work or not, but I think it probably will.
Why do you need to create new local variables in this way anyway? The only reason I can think of for doing it would be interactively in a debugger.
Dave - The Developers' Coach
September 5th, 2004, 12:40 AM
Thanks, Grim and Dave for the replies.
The original application is very much along the lines Dave mentioned: an interractive environment of sorts. I've done a workaround by taking the namespace into a class, but that requires the use of that class name in addition to the variable name of interest. For example: instead of "SomeUserVar = 1", it needs to be "Group1.SomeUserVar = 1". In this particular instance, however, the grouping ended up adding other benefits, so I never bothered about pursuing local namespace after that.
But then, in an IRC channel a couple of days ago, someone needed to create variables in a function's namespace using a string for the variable name. Unfortunately, I don't know what their application was. But this reignited my quest to find a way to access the local namespace dict 'safely'. So, I guess my application at present is mostly just for the principle of the matter, and future use.
BTW, since my first post, I have found a way to implement a dummy __dict__ to access local variables. How 'safe' this implementation is still seems to be questionable, but I tend to agree with Dave that using f_locals seems more reliable than using the dict from locals(). I'll post the implementation of my dummy __dict__ in the tips and tricks thread.