I am trying to enable the user of my drawing program (written in python with pygame) to rename selected objects, then be able to access them through the live interpreter by their names. The following is a method of the base class of all drawable objects. When this code is run, I get no errors, but when I try to access the object through its new name, I am told that the variable with that name is not defined.
Any ideas why this might be?
def rename(self,newName):
"""
Gives this drawable a new name by which the user my reference it in
code
"""
#Create a new variable in the global scope
command = 'global ' + newName + '\n'
#Tie it to me
command += newName + ' = self' + '\n'
#If I already had a name, I'll remove this reference
if self.name != None:
command += 'del ' + self.name
#Execute the command
exec(command)
#Make this adjustment internally
self.name = newName
I don’t think that will work, because the
execfunction has its own conecpt of global variables, independent of the one your function sees.Generally speaking it is easier to manipulate the dictionary of the module. Note that the global scope is actually the member names of the current module.
For example, if you are using the
__main__module, to add a variable:And to delete it:
UPDATE: On second thought, if you don’t care about the module, it is better if you use the
globals()dictionary. To add a variable:And to delete it:
Naturally, that is equivalent to the former, because
globals()returns something like (sys.modules[__name__].__dict__).Nifty. The conclusion is: if you use
evalto do reflection, you are doing it wrong.