Python: create a global variable from a string?

Is there a way to create a global variable from a string? I know that you can make a variable from a string as follows:

string = 'hello' val = 10 vars()[string] = val 

Thus, we assign hello a variable equal to 10. I do not know how to make this user input variable global, however this does not work:

  string = 'hello' val = 10 vars()[string] = val eval("global " + string) 
+6
source share
2 answers

You can use the globals() function:

 name = "hello" globals()[name] = 10 
+13
source

Setting global variables from the module:
I tried something similar, trying to simplify my version of argparse so that it allows minimal duplication of names, support case-insensitive multiple character characters, but still set global variables with mixed flags. The only solution I could come up with was to return a list of statements that I could execute. My attempts to execute a command in a module were unsuccessful. My example:

Self test

 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') 
0
source

Source: https://habr.com/ru/post/916945/


All Articles