Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Create a global variable from a string?

Tags:

python

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)
like image 972
Peter Avatar asked May 29 '12 20:05

Peter


1 Answers

You can use the globals() function:

name = "hello"
globals()[name] = 10
like image 96
6502 Avatar answered Oct 20 '22 14:10

6502