Is there a way to create a global variable from a string? I know that you can make a variable from a string like so:
string = \'hello\'
val = 10
Setting global variables from module:
I tried to something similar in attempt to simplify my version of argparse so it would allow the minimal duplication of names, support case insensitive multiple character flags but still set global variables with mixed case flags.
The Only solution I could come up with was to return a statement list which I could exec. My attempts to exec within the module were not successful.
My example:
def main():
print "Some tests with provided args"
One = 1
Two = 2
Three = 3
prs = ArgumentParserCI(description='process cmdline args')
prs.add_argument('One')
prs.add_argument('Three')
cmdlineargs = ['-one', 'one', '--thr', "III"]
argsdict, unknownargs, execlist = prs.parse_args(cmdlineargs)
exec(execlist)
print("cmdlineargs:", cmdlineargs)
print (One, Two, Three)
if __name__ == "__main__":
main()
Printout:
Some tests with provided args
('cmdlineargs:', ['-one', 'one', '--thr', 'III'])
('one', 2, 'III')
You can use the globals()
function:
name = "hello"
globals()[name] = 10