writing to locals (was RE: execfile: NameError exception thrown for things in locals())

Alex Martelli aleaxit at yahoo.com
Mon Apr 9 16:51:38 EDT 2001


<James_Althoff at i2.com> wrote in message
news:mailman.986840892.29441.python-list at python.org...
    [snip]
>     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'

Just change the line
         localsDict = locals()
to
         localsDict = {}

and the line
            value = eval(self.formula)
to
            value = eval(self.formula, globals(), localsDict)

You don't seem to be using locals() for anything but an auxiliary,
temporary dictionary -- but you can use an _explicitly constructed_
auxiliary dictionary in the same way, just passing it explicitly to
the built-in function eval (the exec statement works similarly, too).


Alex






More information about the Python-list mailing list