Sorry for that confusing title, in my function my parameter is the name I want I want to set as a global variable name. I can do this outside of a function, and I can instantiate a global variable without a string as its name, and I haven't found any other articles with a solution to both problems at the same time.
def myFunc(varName):
temp = varName
# global vars()[temp] <== This line produces the error
vars()[temp] = 5 # varName becomes a local variable
Using global
, like so (notice that some_text
is unknown before the call to fun1
):
def fun1():
global some_text
some_text = "1234"
def fun2():
print(some_text)
fun1()
fun2()
This produces 1234
as one would expect, see a demo on ideone.com .
def myFunc(varName): global TEMP TEMP = varName
Question remains: why would you want to do that? Don't clutter your global namespace with variables only a class/function needs.
You can use the globals
function to achieve this:
def set_global_var(name, value):
globals()[name] = value
if __name__ == '__main__':
set_global_var('foo', 3)
print(foo)
Note that this is most of the case not a good idea. You might want to use a global dict
object instead and simply assign new keys to it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.