How do you dynamically set local variable in Python (where the variable name is dynamic)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Contrary to other answers already posted you cannot modify
locals()directly and expect it to work.Modifying
locals()is undefined. Outside a function whenlocals()andglobals()are the same it will work; inside a function it will usually not work.Use a dictionary, or set an attribute on an object:
or if you prefer, use a class:
Edit:
Access to variables in namespaces that aren’t functions (so modules, class definitions, instances) are usually done by dictionary lookups (as Sven points out in the comments there are exceptions, for example classes that define
__slots__). Function locals can be optimised for speed because the compiler (usually) knows all the names in advance, so there isn’t a dictionary until you calllocals().In the C implementation of Python
locals()(called from inside a function) creates an ordinary dictionary initialised from the current values of the local variables. Within each function any number of calls tolocals()will return the same dictionary, but every call tolocals()will update it with the current values of the local variables. This can give the impression that assignment to elements of the dictionary are ignored (I originally wrote that this was the case). Modifications to existing keys within the dictionary returned fromlocals()therefore only last until the next call tolocals()in the same scope.In IronPython things work a bit differently. Any function that calls
locals()inside it uses a dictionary for its local variables so assignments to local variables change the dictionary and assignments to the dictionary change the variables BUT that’s only if you explicitly calllocals()under that name. If you bind a different name to thelocalsfunction in IronPython then calling it gives you the local variables for the scope where the name was bound and there’s no way to access the function locals through it:This could all change at any time. The only thing guaranteed is that you cannot depend on the results of assigning to the dictionary returned by
locals().