Search code examples
pythonvariablesdynamicglobal

how to create a Python global variable whose name is the value of another variable


Given...

myGlobalVariableName = "zorp"
myGlobalVariableValue = "hello"

, ...how can I use the values of myGlobalVariableName and myGlobalVariableValue to create the global variable "zorp" and set it to "hello"?

The following approach sort-of works, but it's truly horrible:

exec( """
global %s
%s = %r   
""" % (
        myGlobalVariableName,
        myGlobalVariableName, myGlobalVariableValue,
    ),
)

I think maybe my problem is that I don't know how to address the __main__ module object's __dict__ attribute's value. If I knew how to do that, maybe I could simply say:

<main_module_object>.__dict__[ myGlobalVariableName] = myGlobalVariableValue

Anyway, that's the kind of answer I'm looking for, I think.


Solution

  • globals() allows you to modify the global namespace.

    myGlobalVariableName = "zorp"
    myGlobalVariableValue = "hello"
    
    globals()[myGlobalVariableName] = myGlobalVariableValue
    
    print(zorp)
    
    Output:
    hello