-2

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)

  • 4
    You're trying to delete `3`, not `x`. – tkausl Dec 21 '21 at 08:08
  • 2
    Simple way to figure put what's happening: *Print* the strings first. – Some programmer dude Dec 21 '21 at 08:09
  • Sorry (what was really confusing: ```exec("""del {}""".format(name))``` ```SyntaxError: name 'x' is not defined``` edit: note, the code before this text is in the function in the question [code in the question]) –  Dec 21 '21 at 08:21

1 Answers1

2

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)

Akida
  • 1,076
  • 5
  • 16