Python Safe Calculator

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

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s