I have a function:
def globalrn(name, newname):
exec("""global {}""".format(name))
exec("""globals()[newname] = name""")
exec("""del {}""".format(globals()[name])) # using string as a variable name based from answers from https://stackoverflow.com/questions/37717584/how-to-use-string-value-as-a-variable-name-in-python
and the rest of code (not part of function)…
x = 3
globalrn('x', 'y')
print(x)
print(y)
and i get a error:
Traceback (most recent call last):
File "rn", line 8, in <module>
globalrn('x', 'y')
File "rn", line 4, in globalrn
exec("""del {}""".format(globals()[name]))
File "<string>", line 1
SyntaxError: cannot delete literal
I have no idea why is this the case.
(debian/ubuntu, python-3.8)
>Solution :
If I understand you correctly you want to rename a global variable:
You could do this a little bit easier:
globals() gives you access to all global variables in a dictionary, so you can remove a value from the dictionary and insert it with a different key.
def globalrn(name, newname):
globals()[newname] = globals().pop(name)
(.pop(key) removes the entry in the dictionary with the given key and returns its value)