HOWTO · Python
How to Convert a String to Variable Name in Python
In this article we will discuss various ways to convert a string value to a variable name in Python.
On this page
Python does not use the value of a string as the name on the left side of a normal variable assignment. To create or access a name at runtime, choose the namespace that should hold it: globals() for module-level variables, locals() for inspecting local names, exec() for generated source code, setattr() for object attributes, or a dictionary when the names are really data.
Note: Dynamic variable names can hide dependencies, pollute a namespace, and produce a
NameErrorwhen code reads a name that was never created. They are rarely the best choice for production software; prefer a dictionary unless a real global variable or object attribute is required.
Convert a String to a Variable Name Using globals() and locals() in Python
The built-in globals() function returns the dictionary for the current global symbol table. That dictionary maps each global variable’s name to its value. At module scope, writing a new key through this dictionary creates a real global variable with that string as its name.
Run this example:
def create_global_variable(name, value):
globals()[name] = value
variable_name = "dynamicGlobalVar"
variable_value = 10
create_global_variable(variable_name, variable_value)
print(dynamicGlobalVar)
10
The function receives "dynamicGlobalVar" as the name argument and stores 10 under that key in the global symbol table. The later expression dynamicGlobalVar works because the module now has a global variable with that exact name. The string must be a valid Python identifier when source code will access it by name; otherwise retrieve it through globals()[name].
A global name must be created before it is read. If dynamicGlobalVar had not been added to the global symbol table first, the final line would raise a NameError. In real code, prefer a variable such as variable_name for the write instead of embedding an unchecked string throughout the program.
Using locals() to Access a Local Variable
The locals() function returns a mapping that represents the current local symbol table. Inside a function, it is useful for looking up a local name held in a string:
def demonstrate_locals():
temp_var = "Dynamic Content"
name = "temp_var"
return locals().get(name)
print(demonstrate_locals())
Dynamic Content
Here locals().get(name) resolves "temp_var" while the function is running and returns the value of the existing local variable. Using .get() is safer than indexing the mapping directly because it returns None when the requested name is absent.
Do not rely on locals()[name] = value to create a function-local variable. Python implementations are allowed to optimize local variables, and writes to the returned mapping are not required to update the interpreter’s real local bindings. Treat locals() primarily as a lookup and inspection tool; use globals(), setattr(), or a dictionary when the program needs a writable dynamic name.
Convert a String to a Variable Name Using exec() in Python
The exec() function executes Python source code supplied as a string. If that string contains an assignment, running it creates the corresponding variable in the current execution context.
variable_name = "dynamicVar"
value = 42
exec(f"{variable_name} = {value}")
print(dynamicVar)
42
The f-string builds the source text dynamicVar = 42, and exec() runs that assignment. At module level, the result is a new global variable named dynamicVar. When inserting non-numeric values, use repr() or equivalent formatting so the generated source contains a valid Python literal.
exec() is powerful because the string can contain more than a single assignment: it can run loops, imports, function definitions, or arbitrary calls. That power is also its main danger. Never pass user-controlled or otherwise untrusted text to exec(); even a malicious name or value fragment can execute harmful code. Like locals(), exec() also cannot be relied on to update optimized function-local variables, so this technique is clearest at module scope or in an explicit namespace dictionary.
Convert a String to a Variable Name Using setattr() in Python
When the desired “variable” is really an attribute on an object, class, or module, setattr() is the direct tool. It accepts an object, an attribute name as a string, and the value to assign.
class Settings:
pass
settings = Settings()
attribute_name = "theme"
attribute_value = "dark"
setattr(settings, attribute_name, attribute_value)
print(settings.theme)
dark
The call is equivalent to settings.theme = "dark", except that the attribute name comes from attribute_name at runtime. This is useful for configuration objects, records, plugin hooks, and other places where a namespace object is already part of the design.
setattr() does not create an ordinary module or function variable; it updates the target object’s attribute namespace. Use getattr(settings, attribute_name) to read the value dynamically, or getattr(settings, attribute_name, default_value) when a fallback is needed.
Use a Dictionary Instead of Dynamic Variable Names in Python
A dictionary is usually the clearest answer when a program stores values under names known only at runtime. The string remains a key, so the collection of dynamic names stays explicit and easy to inspect.
dynamic_vars = {}
var_name = "temperature"
var_value = 23
dynamic_vars[var_name] = var_value
print(dynamic_vars["temperature"])
23
This creates the same association as a variable named temperature holding 23, but without adding names to a Python namespace. Keys can be listed, passed to another function, serialized, or removed without searching globals() for unexpected entries.
Dictionary keys also are not limited to Python identifier rules, so names such as "daily total" can be used as data. Access a required key with dynamic_vars[var_name], or use dynamic_vars.get(var_name) when an absent key should produce a fallback rather than fail. This avoids NameError handling because the program is querying a data structure rather than resolving source-level variables.
Conclusion
Python offers several ways to turn a runtime string into a usable name. globals() can create a real module-level variable through the global symbol table. locals() can look up local names, but it is unreliable as a write mechanism. exec() can execute a generated assignment, although it carries the greatest security and clarity risks. setattr() is appropriate when the dynamic name belongs on an object or module.
For most programs, a dictionary is the safest and most maintainable choice. It keeps dynamic names as data, avoids polluting Python namespaces, and makes missing-name behavior explicit. Reserve real dynamic variables or attributes for designs that genuinely require them.