Implement safe_eval() in order to armour eval()
[odoo/odoo.git] / bin / tools / safe_eval.py
1 # -*- encoding: utf-8 -*-
2 #
3 # Copyright P. Christeas <p_christ@hol.gr> 2008,2009
4 #
5 #
6 # WARNING: This program as such is intended to be used by professional
7 # programmers who take the whole responsability of assessing all potential
8 # consequences resulting from its eventual inadequacies and bugs
9 # End users who are looking for a ready-to-use solution with commercial
10 # garantees and support are strongly adviced to contract a Free Software
11 # Service Company
12 #
13 # This program is Free Software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation; either version 2
16 # of the License, or (at your option) any later version.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26 ###############################################################################
27
28 __export_bis = {}
29
30 def __init_ebis():
31         global __export_bis
32         
33         _evars = [ 'abs', 'all', 'any', 'basestring' , 'bin', 'bool', 
34                 'chr', 'cmp','complex', 'dict', 'divmod', 'enumerate',
35                 'float','format', 'frozenset', 'getattr', 'hasattr', 'hash',
36                 'hex', 'id','int', 'iter', 'len', 'list', 'long', 'map', 'max',
37                 'min','next', 'oct', 'ord','pow', 'range', 'reduce', 'repr',
38                 'reversed', 'round', 'set', 'setattr', 'slice','sorted', 'str',
39                 'sum', 'tuple','type', 'unichr','unicode', 'xrange',
40                 'True','False', 'None', 'NotImplemented', 'Ellipsis', ]
41                 
42         for v in _evars:
43                 __export_bis[v] = __builtins__[v]
44         
45
46 __init_ebis()
47
48
49 def safe_eval(expr,sglobals,slocals = None):
50         """ A little safer version of eval().
51             This one, will use fewer builtin functions, so that only
52             arithmetic and logic expressions can really work """
53         
54         global __export_bis
55
56         if not sglobals.has_key('__builtins__'):
57                 # we copy, because we wouldn't want successive calls to safe_eval
58                 # to be able to alter the builtins.
59                 sglobals['__builtins__'] = __export_bis.copy()
60                 
61         return eval(expr,sglobals,slocals)
62         
63 #eof