Python: Create a global variable from a string?

后端 未结 2 1687
独厮守ぢ
独厮守ぢ 2020-12-20 15:24

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
             


        
相关标签:
2条回答
  • 2020-12-20 15:49

    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:

    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 讨论(0)
  • 2020-12-20 15:55

    You can use the globals() function:

    name = "hello"
    globals()[name] = 10
    
    0 讨论(0)
提交回复
热议问题