Use eval() to drive spreadsheet style logic. The sleeper feature of Py2.4 is the ability to use any object with a mapping interface as the locals argument to eval().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class SpreadSheet:
_cells = {}
tools = {}
def __setitem__(self, key, formula):
self._cells[key] = formula
def getformula(self, key):
return self._cells[key]
def __getitem__(self, key ):
return eval(self._cells[key], SpreadSheet.tools, self)
>>> from math import sin, pi
>>> SpreadSheet.tools.update(sin=sin, pi=pi, len=len)
>>> ss = SpreadSheet()
>>> ss['a1'] = '5'
>>> ss['a2'] = 'a1*6'
>>> ss['a3'] = 'a2*7'
>>> ss['a3']
210
>>> ss['b1'] = 'sin(pi/4)'
>>> ss['b1']
0.70710678118654746
>>> ss.getformula('b1')
'sin(pi/4)'
|
The _cells dictionary maps cell addresses to formulas. Looking up the cell triggers an eval on that cell formula, possibly resulting in other cells being looked up and evaluated.
The tools class variable is a dictionary of functions and constants you want to make visible to users of the spreadsheet. This doesn't make eval() totally secure, but it improves the situation somewhat.
This is meant to be a minimal example to show the basic idea. The idea scales up well. Without too much effort, I've built out a modest spreadsheet program with error trapping, limited access to globals, handling of circular references, strings, summations, a library of spreadsheet functions, the ability to save and restore (using pickle), and a TkInter GUI that looks and acts like a regular spreadsheet.
You may or may not want to use globals(). This is an example of why I like languages with "eval". ;) To be on the safe side, you may want not to use globals() as a simple
will delete an important file.
In short, if you are not very careful with evaluation, a bad spreadsheet may really mess up your system.
If you want to allow this depends on how much you trust your users.
really kewl! But I had to move things around a bit to determine that the math module wasn't part of the class. Here's how I have it rearranged it right now - this way I could also obviously use it with decimal or datetime or whatever I need to, but that I don't have to import anything for the class itself.
Make it work in Python 2.3 & restrict eval. By catching NameError, you can make this work even under Python 2.3. It would also be possible to modify it a bit to easily detect infinite loops. The code below shows how to further restrict what kind of formulas you use in a cell by setting __builtins__ to None in the tools dict. (This disallows the nastiness Andreas pointed out above.)
Here's my take on it. It works on 2.3, it supports cell dependencies, automatically recalculates when needed, caches compiled versions of the formulae, and a couple of other things.
Sadly, that bloats it to about 100LOC, but I don't think that's too bad for a almost-working spreadsheet!
It has some PyQt-ism somewhere, feel free to ignore them. And feel free to fix what may be broken ;-)
(comment continued...)
(...continued from previous comment)
Resolver IronPython Spreadsheet. There is an IronPython application that has taken this idea many steps further:
http://www.resolversystems.com
http://www.resolverhacks.net
You have the API to create the spreadsheet programmatically, or the grid to enter data and formulae - which are translated into Python code!
Ray's spreadsheet is brilliant. I wish I could think of such concise algorithms. If I were ambitious I'd insert a __str__ method.
But everybody knows--formulas start with '='!
This is a marvelous, elegant recipe. I decided to tweak it slightly, to more closely mirror real spreadsheets--which require an = on the front of a live expression. I also store static values in their native types, instead of as strings. Internally I store live expressions as strings without the '=' (so I don't have to slice it each time I eval it) and static values as a one-element tuple. Sadly, this meant the code is slightly less elegant.
(p.s. It works unchanged in Python 2.6 and 3.0!)
Do the codes work on Python 2.5? My work mainly involves using 2.5, and it would be nice if they would work on Py2.5...
Thanks in advance!
Dee
Hello Dee. Yes, it should work just fine on {ython 2.5.
s["a1"] = 'exec("import os; os.unlink(\"really_important_file\")")'
Try pysandbox to avoid this kind of problem: https://github.com/haypo/pysandbox