Accessing Dynamically Set Local Variables in Python
Despite previous suggestions, direct modification of local variables through locals() is unreliable and undefined. Instead, several practical approaches can be employed to achieve dynamic local variable manipulation.
Dictionary Manipulation
Utilize a dictionary to assign and access dynamic local variables:
d = {} d['xyz'] = 42 print(d['xyz'])
Object Attributes
Set attributes on an object to create dynamic local variables:
class C: pass obj = C() setattr(obj, 'xyz', 42) print(obj.xyz)
Note:
Accessing variables in non-function namespaces (modules, class definitions, instances) typically involves dictionary lookups. Function locals can be optimized for speed, and direct modification of locals() within a function is generally not possible.
IronPython Exception
In IronPython, explicitly calling locals() returns the local variables as a dictionary. Binding a different name to locals within a function grants access to the local variables of the binding scope.
Conclusion
Employing dictionaries or object attributes provides reliable methods for dynamically setting local variables in Python. Avoid relying on direct modification of locals() to prevent unpredictable behavior.
The above is the detailed content of How Can I Dynamically Set and Access Local Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!