Python Safe Calculator

2007 December 17
by Tzury Bar Yochay

Web-Safe Arithmetic Expressions Evaluator

import math
import re

whitelist = '|'.join(
    # oprators, digits
    ['-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '\d+']
    # functions of math module (ex. __xxx__)
    + [f for f in dir(math) if f[:2] != '__'])

valid = lambda exp: re.match(whitelist, exp)

>>> valid('23**2')
<_sre.SRE_Match object at 0xb78ac218>
>>> valid('sys.exit(100)') == None
True
>>> exp = '23**2'
>>> if valid(exp):
>>>     x = eval(exp)

came across this post via unofficial planet python

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS