Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python3: SyntaxError: cannot delete literal

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading