I don't think anyone has explained how to create and set a global variable whose name is itself the value of a variable.
Here's an answer I don't like, but at least it works[1], usually[2].
I wish someone would show me a better way to do it. I have found several use cases and I'm actually using this ugly answer:
########################################
def insert_into_global_namespace(
new_global_name,
new_global_value = None,
):
executable_string = """
global %s
%s = %r
""" % (
new_global_name,
new_global_name, new_global_value,
)
exec executable_string ## suboptimal!
if __name__ == '__main__':
## create global variable foo with value 'bar':
insert_into_global_namespace(
'foo',
'bar',
)
print globals()[ 'foo']
########################################
Python exec should be avoided for many reasons.
N.B.: Note the lack of an "in" keyword on the "exec" line ("unqualified exec").