15

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
    vars()[string] = val

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

    string = 'hello'
    val = 10
    vars()[string] = val
    eval("global " + string)
3
  • 8
    Why do you need this? Why don't you use a dictionary? That would be much cleaner. Commented May 29, 2012 at 20:34
  • Just as a side observation: in over a decade writing Python, I've never - literally not once - ever needed to do anything remotely close to this. Commented May 29, 2012 at 23:53
  • 3
    Why do you criticize this question? There are surely legitimate uses for this. And if not, knowing how it can be done from a purely curious standpoint is legitimate as well, is it not? Commented Sep 10, 2019 at 23:19

2 Answers 2

31

You can use the globals() function:

name = "hello"
globals()[name] = 10
Sign up to request clarification or add additional context in comments.

4 Comments

@user1424641 check as answer then ?
@user1424641: If you have to do this, there is probably something wrong with your implementation.
I thought this method was extremely unsafe... I'm trying to set globals in a local (module) namespace... not sure if sys.modules[current_module] would be a good spot to define the global name.
EDIT: oh, it's clarified here: stackoverflow.com/questions/13311033/…
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.