Home >Backend Development >Python Tutorial >How Can I Dynamically Assign Local Variables in Python?
Dynamic Variable Assignment in Python
In Python, dynamically setting local variables by directly modifying the locals() dictionary is not a viable solution. Contrary to popular belief, any such modifications will not persist within the function's scope.
Alternative Approaches
To dynamically set local variables, consider using any of the following methods:
Dictionary
Create a dictionary and assign key-value pairs dynamically:
d = {} d['xyz'] = 42
Object Attribute
Use an object and set attributes dynamically:
class C: pass obj = C() setattr(obj, 'xyz', 42)
Edit
Accessing variables in non-function namespaces (modules, class definitions, instances) typically involves dictionary lookups. However, function locals are optimized for speed by pre-compiling the variable names known to the compiler.
In the C implementation of Python, calling locals() within a function creates a dictionary initialized with current local variable values. This dictionary is updated with changes to local variables and returned upon subsequent calls to locals().
In IronPython, functions calling locals() use a dictionary as their local variables store. Assignments to local variables alter the dictionary, and vice versa. However, binding a different name to the locals function within IronPython allows access to the local variables of the binding scope, not the function's.
Caution
It's important to note that assigning to the dictionary returned by locals() can produce unpredictable results. Relying on these assignments is strongly discouraged.
The above is the detailed content of How Can I Dynamically Assign Local Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!