writing to locals (was RE: execfile: NameError exception thrown for things in locals())
James_Althoff at i2.com
James_Althoff at i2.com
Mon Apr 9 14:27:45 EDT 2001
< Tim informs ...>
> So this is what you can expect (or rail against) in the indefinite
future:
>
> 1. Python will eventually enforce the Ref Man's warnings against trying
> to modify locals(), whether directly or indirectly.
uh-oh ... I guess I'm in violation of the intended policy.
I have a class that acts as a poor-man's spreadsheet in a GUI application.
I show a table and label the column headers as c1, c2, ...
For the last column (rightmost) I allow the user to input a formula such as
c1/c2 and use it to compute the values for that (rightmost) column.
A simplified version of the code (please excuse typo.s) looks like:
... my class ...
def setFormula(self,formulaString):
self.formula = formulaString
def getCalculatedValueAt(self,rowIndex):
count = self.getColumnCount() # excludes the calculated column
localsDict = locals()
for columnIndex in xrange(count):
columnID = 'c' + str(columnIndex+1)
columnValue = self.getValueAt(rowIndex,columnIndex)
localsDict[columnID] = columnValue
try:
value = eval(self.formula)
except:
value = 'Invalid formula'
return value
It seems like the alternatives are:
o build up an assignment statement in a string and do an
exec (yuk, columnValue is already a perfectly good object)
o use the instance dict and then preprocess
the formula to change (e.g.) c1 to self.c1 (yuk)
o use globals() and then add another loop at the end to
delete the newly created global variables (to avoid
interference with other instances of the class)
I guess using globals() is ok, but locals() seems so much nicer. :-)
Any other suggestions?
Thanks,
Jim
More information about the Python-list
mailing list