Executing mathematical user inputed statements as code in Python 3 - python-3.x

How would one allow the user to input a statement such as "math.sin(x)**2" and calculate the answer within python code.
In telling me the answer please explain why both exec() compile() are not producing the desired result.
import math
def getValue(function, x):
function = "val = " + function
#compile(function, '', 'exec')
exec(function)
print(val)
function = input("Enter a function f(x):\n")
getValue(function, 10)
Much Appreciated!

To answer your question, use eval:
>>> eval('math.sin(1)**2')
0.7080734182735712
exec is working, but you are not retrieving the result. Notice:
>>> val
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'val' is not defined
>>> exec('val=math.sin(1)**2')
>>> val
0.7080734182735712
So, using eval instead of exec works like so:
def getValue(function, x):
function = "{}({})".format(function, x)
print(function)
val=eval(function)
print(val)
That said -- it is considered an extreme security risk to execute arbitrary user code.
If you are building a calculator, a safer approach you might consider using SymPy or building your own parser using something like PyParsing (which is used in SymPy)
An example PyParsing calculator:
import sys
import operator
from pyparsing import nums, oneOf, Word, Literal, Suppress
from pyparsing import ParseException, Forward, Group
op_map = { '*' : operator.mul,\
'+' : operator.add,\
'/' : operator.div,\
'-' : operator.sub}
exp = Forward()
number = Word(nums).setParseAction(lambda s, l, t: int(t[0]))
lparen = Literal('(').suppress()
rparen = Literal(')').suppress()
op = oneOf('+ - * /').setResultsName('op').setParseAction(lambda s, l, t: op_map[t[0]])
exp << Group(lparen + op + (number | exp) + (number | exp) + rparen)
def processArg(arg):
if isinstance(arg, int):
return arg
else:
return processList(arg)
def processList(lst):
args = [processArg(x) for x in lst[1:]]
return lst.op(args[0], args[1])
def handleLine(line):
result = exp.parseString(line)
return processList(result[0])
while True:
try:
print handleLine(raw_input('> '))
except ParseException, e:
print >>sys.stderr,\
"Syntax error at position %d: %s" % (e.col, e.line)
except ZeroDivisionError:
print >>sys.stderr,\
"Division by zero error"
Which can easily be extended to include other functions.

Related

Python regular expressions: Better way to handle non-matches?

When I deal with regular expressions, my code is littered with conditionals so as to not create exceptions when a pattern is not found:
m = some_compiled_pattern.match(s)
if m:
x = m.groups()
do_something_with(x)
m = some_other_compiled_pattern.search(s):
if m:
y = m.groupdict()
else:
y = {}
do_something_else_with(y)
Isn't there a better (less verbose) way to handle such exceptions?
You might find this class useful to reduce most of those if-no-match handling to a one line.
class Returns:
"""
Makes an object that pretends to have all possible methods,
but returns the same value (default None) no matter what this method,
or its arguments, is.
"""
def __init__(self, return_val=None):
self.return_val = return_val
def the_only_method_there_is(*args, **kwargs):
return return_val
self.the_only_method_there_is = MethodType(the_only_method_there_is, self)
def __getattr__(self, item):
if not item.startswith('_') and item not in {'return_val', 'the_only_method_there_id'}:
return self.the_only_method_there_is
else:
return getattr(self, item)
Example use:
>>> import re
>>> p = re.compile(r'(\d+)\W+(\w+)')
>>>
>>> # when all goes well...
>>> m = p.search('The number 42 is mentioned often')
>>> num, next_word = m.groups()
>>> num, next_word
('42', 'is')
>>>
>>> # when the pattern is not found...
>>> m = p.search('No number here')
>>> assert m is None # m is None so...
>>> num, next_word = m.groups() # ... this is going to choke
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'groups'
>>>
>>> # Returns to the rescue
>>> num, next_word = (p.search('No number here') or Returns((None, 'default_word'))).groups()
>>> assert num is None
>>> next_word
'default_word'
EDIT: See this gist for a longer discussion (and alternate but similar solution) of this problem.

Can't convert complex to float on python 3

I write this code for uri online judge(problem no.1036)...It is an Bhaskara's formula...
import cmath
A,B,C=input().split()
A = float(A)
B = float(B)
C = float(C)
D = (B*B)-(4*A*C)
if((D== -D)|(A==0)):
print("Impossivel calcular")
else:
T = cmath.sqrt(D)
x1 = (-B+T)/(2*A)
x2 = (-B-T)/(2*A)
print("R1 = %.5f" %x1)
print("R2 = %.5f" %x2)
but when i submit this program...that runtime error occured...
Traceback (most recent call last): File "Main.py", line 14, in
print("R1 = %.5f" %x1)
TypeError: can't convert complex to float
Command exited with non-zero status (1)
please help me to solve this problem.
The problem with using sqrt imported from cmath is that it outputs a complex number, which cannot be converted to float. If you are calculating a sqrt from positive number, use math library (see below).
>>> from cmath import sqrt
>>> sqrt(2)
(1.4142135623730951+0j)
>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951
the problem is just that your format string is for floats and not for complex numbers. something like this will work:
print('{:#.3} '.format(5.1234 + 4.123455j))
# (5.12+4.12j)
or - more explicit:
print('{0.real:.3f} + {0.imag:.3f}i'.format(5.123456789 + 4.1234556547643j))
# 5.123 + 4.123i
you may want to have a look at the format specification mini language.
# as format specifier will not work with the old-style % formatting...
then there are more issues with your code:
if((D== -D)|(A==0)):
why not if D==0:? and for that it might be better to use cmath.isclose.
then: | is a bit-wise operator the way you use it; you may want to replace it with or.
your if statement could look like this:
if D == 0 or A == 0:
# or maybe
# if D.isclose(0) or A.isclose():

Automated Testing Reverse String in Python 3

I am trying to create a function that can test two different functions.
I am naming my test function test_reverse, to automate testing of strReverseI and strReverseR (see the code for these below)
strReverseI and strReverseR will be arguments to test_reverse.
test_reverse will have one parameter, f, a function (either strReverseR or strReverseI)
test_reverse will call f repeatedly, for a series of test cases, and compare the result returned by either strReverseR or strReverseI to the expected result.
test_reverse should report for each test case whether the actual result matches the expected result, e.g.,
Checking strReverseR('testing123')...its value '321gnitset' is correct!
Checking strReverseI('a')... Error: has wrong value 'a', expected 'b'.
Function test_reverse should return None.
Test cases and expected results should be stored in a tuple of tuples defined in test_reverse. test_reverse should include at least the following tests:
(
('', ''),
('a', 'a'),
('aaaa', 'aaaa'),
('abc', 'cba'),
('hello', 'olleh'), ('racecar', 'racecar'),
('testing123', '321gnitset'), ('#CIS 210', '012 SIC#'), ('a', 'b')
)
Here is the code I have so far… strReverseR and strReverseI work perfectly, I am not just needing to figure out test_reverse:
import doctest
def strReverseI(s):
'''
(str) -> (str)
Returns the reverse of the string input. This function finds
the reverse string via an interative implementation.
NOTE TO MYSELF: I could also have chosen to do a while loop being
(s[n:] != ''):
This is using a while loop and as long as the slice of the string
is not an empty string,
it will continue to run the loop. As soon as the slice becomes an
empty string,
it will stop the loop and you will have the reverse string.
Examples:
>>> strReverseI('hello, world')
'dlrow ,olleh'
>>> strReverseR('')
''
>>> strReverseR('a')
'a'
'''
result = ""
n = 0
for i in range(1, len(s) + 1):
result += s[len(s) - i]
return result
def strReverseR(s):
'''
(str) -> (str)
Returns the reverse of the string input. This function finds
the reverse string via recuersion. The base case would be an empty
string so the function would still return out an empty string and
not have any errors.
After we can confirm the string is not empty,
we return the last element of the string, followed by
the string without that last element/character. Since this
continues to call upon itself, it will continue to cut the string
of the "last" element to grow the reverse string.
Examples:
>>> strReverseR('hello, world')
'dlrow ,olleh'
>>> strReverseR('')
''
>>> strReverseR('a')
'a'
'''
if s == '':
return s
result = s[-1] + strReverseR(s[0:-1])
return result
def test_reverse(f):
'''
function ->
'''
if f('hi') == 'ih':
print("success")
else:
print("failed")
return None
Note Yes, this is something I am working on for a school hw assignment. I am not expecting anyone to write it for me. I am just really confused on this last part and would love some insight on how to move forward. Any examples, and explanations would be so helpful. Thanks.
Update I have been working on this more and this is along the lines of what I think I need to do, if you could help a bit with this that would be great!
def test_reverse(f):
'''
function ->
'''
list = (
('', ''),
('a', 'a'),
('aaaa', 'aaaa'),
('abc', 'cba'),
('hello', 'olleh'), ('racecar', 'racecar'),
('testing123', '321gnitset'), ('#CIS 210', '012 SIC#'), ('a', 'b')
)
for x in list:
#f(i[0]) = [1])
if f(i[0] == [1]):
print("Checking", f,"... its value", "is correct!")
else:
print("Checking", f, "... Error: has wrong value")
return None
def main():
'''calls string reverse test func 2 times'''
test_reverse(p5.strReverseR)
print()
test_reverse(p5.strReverseI)
return None
You should consider using a tool like unittest for this - it has assert style tests which make calling methods and seeing their output easy.
For your use case, you probably want to create tests.py, something like:
import unittest
from myreversemodule import strReverseL, strReverseR
class ReverseTestCase(unittest.TestCase):
def test_strreverser(self):
self.assertEqual(strReverseR('hi'), 'ih')
if __name__ == "__main__":
unittest.main()
Now run this script - and it will give you nice test output, show errors, return True or False if it succeeds/fails. You can also run specific tests by name if you only want to test a subset, and use setUp/tearDown methods to do some config before/after running each test/each suite of tests.
Without inherited of unittest you can use builtins AssertionError:
def test_case(first_string, reversed_string):
if strReverseR(first_string) != reversed_string:
raise AssertionError("Reverse of first string: " + strReverseR(first_string) + " are not equals to second string: " + reversed_string)
Hope, it helps.
import p52_stringreverse as p5 # this is importing my strReverseR and strReverseI from a different py file, but the code for those are posted in my question anyway.
def test_reverse(f):
'''
function -> None
'''
testingcases = (('', ''), ('a', 'a'), ('aaaa', 'aaaa'),
('abc', 'cba'), ('hello', 'olleh'), ('racecar', 'racecar'),
('testing123', '321gnitset'), ('#CIS 210', '012 SIC#'), ('a', 'b'))
for case in testingcases:
if f(case[0]) == case[1]:
print("Checking", f.__name__ + "(" + "'" + case[0] + "'" + ")",
"... its value", "'" + case[1] + "'", "is correct!")
else:
print("Checking", f.__name__ + "(" + "'" + case[0] + "'" + ")",
"... Error: has wrong value", "'" + case[0] + "'" + ",", "expected",
"'" + case[1] + "'")
return None
def main():
'''calls string reverse test func 2 times'''
test_reverse(p5.strReverseR)
print()
test_reverse(p5.strReverseI)
return None
main()

Function not allowing 2nd argument

I made a logging function , which takes 2 arguments: log_message and mode. For some reason, when I use the function and pass arguments, I get the following error:
Traceback (most recent call last):
File "/Users/user/git/rip/rip.py", line 248, in <module>
main()
File "/Users/user/git/rip/rip.py", line 195, in main
log('STARTING RIPPER', 'i')
TypeError: log() takes 1 positional argument but 2 were given
Which is strange, since log() definitely takes 2 arguments.
Here is my code:
import os
import sys
import time
import mmap
import json
import requests
from bs4 import BeautifulSoup
from clint.textui import puts, colored
def log(log_message, mode='s'):
log_date = '[' + time.strftime("%d.%m_%H:%M:%S") + ']'
if mode == 'e':
log_file = 'test_error.log'
log_ouput = colored.white(log_date) + colored.red('[ERROR]' + log_message)
elif mode == 'i':
log_file = 'test_info.log'
log_ouput = colored.white(log_date) + colored.yellow('[INFO]' + log_message)
elif mode == 'c':
log_file = 'test_info.log'
log_ouput = colored.white(log_date) + colored.white('[COMMENT]' + log_message)
else:
log_file = 'test_download.log'
log_ouput = colored.white(log_date) + colored.green(log_message)
with open(log_file, 'a') as file_writer:
file_writer.write(log_message + '\n')
file_writer.close()
puts(log_ouput)
def main():
log('STARTING RIPPER', 'i')
Maybe your interpreter (and don't know why) thinks that 'i' is also a positonal argument (argument function with no name).
Try writing instead
log('STARTING RIPPER', mode='i')
And given that, btw, explicit is better than implicit, you should even write
log(log_message='STARTING RIPPER', mode='i')
This minimal example works for me:
def log(log_message, mode='s'):
print(log_message, mode)
log('STARTING RIPPER', 'i')
I think the log you are calling is a different log. Try
print(log.__module__)
to find out where the function comes from.
Edit:
To make sure that the signature of your function is what you expect, you can use
import inspect
print(inspect.signature(log))
which should return
(log_message, mode='s')

How to convert mathematical strings into a solvable sum in python 3 [duplicate]

stringExp = "2^4"
intVal = int(stringExp) # Expected value: 16
This returns the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
with base 10: '2^4'
I know that eval can work around this, but isn't there a better and - more importantly - safer method to evaluate a mathematical expression that is being stored in a string?
eval is evil
eval("__import__('os').remove('important file')") # arbitrary commands
eval("9**9**9**9**9**9**9**9", {'__builtins__': None}) # CPU, memory
Note: even if you use set __builtins__ to None it still might be possible to break out using introspection:
eval('(1).__class__.__bases__[0].__subclasses__()', {'__builtins__': None})
Evaluate arithmetic expression using ast
import ast
import operator as op
# supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
def eval_expr(expr):
"""
>>> eval_expr('2^6')
4
>>> eval_expr('2**6')
64
>>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0
"""
return eval_(ast.parse(expr, mode='eval').body)
def eval_(node):
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return operators[type(node.op)](eval_(node.operand))
else:
raise TypeError(node)
You can easily limit allowed range for each operation or any intermediate result, e.g., to limit input arguments for a**b:
def power(a, b):
if any(abs(n) > 100 for n in [a, b]):
raise ValueError((a,b))
return op.pow(a, b)
operators[ast.Pow] = power
Or to limit magnitude of intermediate results:
import functools
def limit(max_=None):
"""Return decorator that limits allowed returned values."""
def decorator(func):
#functools.wraps(func)
def wrapper(*args, **kwargs):
ret = func(*args, **kwargs)
try:
mag = abs(ret)
except TypeError:
pass # not applicable
else:
if mag > max_:
raise ValueError(ret)
return ret
return wrapper
return decorator
eval_ = limit(max_=10**100)(eval_)
Example
>>> evil = "__import__('os').remove('important file')"
>>> eval_expr(evil) #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
>>> eval_expr("9**9")
387420489
>>> eval_expr("9**9**9**9**9**9**9**9") #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError:
Pyparsing can be used to parse mathematical expressions. In particular, fourFn.py
shows how to parse basic arithmetic expressions. Below, I've rewrapped fourFn into a numeric parser class for easier reuse.
from __future__ import division
from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional,
ZeroOrMore, Forward, nums, alphas, oneOf)
import math
import operator
__author__ = 'Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20 $'
__source__ = '''http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
'''
__note__ = '''
All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
more easily in other places.
'''
class NumericStringParser(object):
'''
Most of this code comes from the fourFn.py pyparsing example
'''
def pushFirst(self, strg, loc, toks):
self.exprStack.append(toks[0])
def pushUMinus(self, strg, loc, toks):
if toks and toks[0] == '-':
self.exprStack.append('unary -')
def __init__(self):
"""
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
"""
point = Literal(".")
e = CaselessLiteral("E")
fnumber = Combine(Word("+-" + nums, nums) +
Optional(point + Optional(Word(nums))) +
Optional(e + Word("+-" + nums, nums)))
ident = Word(alphas, alphas + nums + "_$")
plus = Literal("+")
minus = Literal("-")
mult = Literal("*")
div = Literal("/")
lpar = Literal("(").suppress()
rpar = Literal(")").suppress()
addop = plus | minus
multop = mult | div
expop = Literal("^")
pi = CaselessLiteral("PI")
expr = Forward()
atom = ((Optional(oneOf("- +")) +
(ident + lpar + expr + rpar | pi | e | fnumber).setParseAction(self.pushFirst))
| Optional(oneOf("- +")) + Group(lpar + expr + rpar)
).setParseAction(self.pushUMinus)
# by defining exponentiation as "atom [ ^ factor ]..." instead of
# "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
# that is, 2^3^2 = 2^(3^2), not (2^3)^2.
factor = Forward()
factor << atom + \
ZeroOrMore((expop + factor).setParseAction(self.pushFirst))
term = factor + \
ZeroOrMore((multop + factor).setParseAction(self.pushFirst))
expr << term + \
ZeroOrMore((addop + term).setParseAction(self.pushFirst))
# addop_term = ( addop + term ).setParseAction( self.pushFirst )
# general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term)
# expr << general_term
self.bnf = expr
# map operator symbols to corresponding arithmetic operations
epsilon = 1e-12
self.opn = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"^": operator.pow}
self.fn = {"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"exp": math.exp,
"abs": abs,
"trunc": lambda a: int(a),
"round": round,
"sgn": lambda a: abs(a) > epsilon and cmp(a, 0) or 0}
def evaluateStack(self, s):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack(s)
if op in "+-*/^":
op2 = self.evaluateStack(s)
op1 = self.evaluateStack(s)
return self.opn[op](op1, op2)
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op](self.evaluateStack(s))
elif op[0].isalpha():
return 0
else:
return float(op)
def eval(self, num_string, parseAll=True):
self.exprStack = []
results = self.bnf.parseString(num_string, parseAll)
val = self.evaluateStack(self.exprStack[:])
return val
You can use it like this
nsp = NumericStringParser()
result = nsp.eval('2^4')
print(result)
# 16.0
result = nsp.eval('exp(2^4)')
print(result)
# 8886110.520507872
Some safer alternatives to eval() and sympy.sympify().evalf()*:
asteval
numexpr
*SymPy sympify is also unsafe according to the following warning from the documentation.
Warning: Note that this function uses eval, and thus shouldn’t be used on unsanitized input.
The reason eval and exec are so dangerous is that the default compile function will generate bytecode for any valid python expression, and the default eval or exec will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.
Instead, you can easily create a simple eval function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.
c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]
The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d, which is the bytecode for LOAD_CONST, followed by the number of the constant to load (usually the last one in the list), followed by S, which is the bytecode for RETURN_VALUE. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).
This also opens the door to some more sophisticated input formats. For example:
stringExp = "1 + cos(2)"
This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS) or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION only allow functions in a 'safe' list.
from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator
globs = {'sin':sin, 'cos':cos}
safe = globs.values()
stack = LifoQueue()
class BINARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get(),stack.get()))
class UNARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get()))
def CALL_FUNCTION(context, arg):
argc = arg[0]+arg[1]*256
args = [stack.get() for i in range(argc)]
func = stack.get()
if func not in safe:
raise TypeError("Function %r now allowed"%func)
stack.put(func(*args))
def LOAD_CONST(context, arg):
cons = arg[0]+arg[1]*256
stack.put(context['code'].co_consts[cons])
def LOAD_NAME(context, arg):
name_num = arg[0]+arg[1]*256
name = context['code'].co_names[name_num]
if name in context['locals']:
stack.put(context['locals'][name])
else:
stack.put(context['globals'][name])
def RETURN_VALUE(context):
return stack.get()
opfuncs = {
opmap['BINARY_ADD']: BINARY(operator.add),
opmap['UNARY_INVERT']: UNARY(operator.invert),
opmap['CALL_FUNCTION']: CALL_FUNCTION,
opmap['LOAD_CONST']: LOAD_CONST,
opmap['LOAD_NAME']: LOAD_NAME
opmap['RETURN_VALUE']: RETURN_VALUE,
}
def VMeval(c):
context = dict(locals={}, globals=globs, code=c)
bci = iter(c.co_code)
for bytecode in bci:
func = opfuncs[ord(bytecode)]
if func.func_code.co_argcount==1:
ret = func(context)
else:
args = ord(bci.next()), ord(bci.next())
ret = func(context, args)
if ret:
return ret
def evaluate(expr):
return VMeval(compile(expr, 'userinput', 'eval'))
Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST and a couple others would allow for input like 'x=5;return x+x or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto bytecodes, which means changing from a for iterator to while and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER being the most obvious).
While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile take anything arbitrarily complicated and reduces it to a sequence of simple instructions).
Okay, so the problem with eval is that it can escape its sandbox too easily, even if you get rid of __builtins__. All the methods for escaping the sandbox come down to using getattr or object.__getattribute__ (via the . operator) to obtain a reference to some dangerous object via some allowed object (''.__class__.__bases__[0].__subclasses__ or similar). getattr is eliminated by setting __builtins__ to None. object.__getattribute__ is the difficult one, since it cannot simply be removed, both because object is immutable and because removing it would break everything. However, __getattribute__ is only accessible via the . operator, so purging that from your input is sufficient to ensure eval cannot escape its sandbox.
In processing formulas, the only valid use of a decimal is when it is preceded or followed by [0-9], so we just remove all other instances of ..
import re
inp = re.sub(r"\.(?![0-9])","", inp)
val = eval(inp, {'__builtins__':None})
Note that while python normally treats 1 + 1. as 1 + 1.0, this will remove the trailing . and leave you with 1 + 1. You could add ),, and EOF to the list of things allowed to follow ., but why bother?
You can use the ast module and write a NodeVisitor that verifies that the type of each node is part of a whitelist.
import ast, math
locals = {key: value for (key,value) in vars(math).items() if key[0] != '_'}
locals.update({"abs": abs, "complex": complex, "min": min, "max": max, "pow": pow, "round": round})
class Visitor(ast.NodeVisitor):
def visit(self, node):
if not isinstance(node, self.whitelist):
raise ValueError(node)
return super().visit(node)
whitelist = (ast.Module, ast.Expr, ast.Load, ast.Expression, ast.Add, ast.Sub, ast.UnaryOp, ast.Num, ast.BinOp,
ast.Mult, ast.Div, ast.Pow, ast.BitOr, ast.BitAnd, ast.BitXor, ast.USub, ast.UAdd, ast.FloorDiv, ast.Mod,
ast.LShift, ast.RShift, ast.Invert, ast.Call, ast.Name)
def evaluate(expr, locals = {}):
if any(elem in expr for elem in '\n#') : raise ValueError(expr)
try:
node = ast.parse(expr.strip(), mode='eval')
Visitor().visit(node)
return eval(compile(node, "<string>", "eval"), {'__builtins__': None}, locals)
except Exception: raise ValueError(expr)
Because it works via a whitelist rather than a blacklist, it is safe. The only functions and variables it can access are those you explicitly give it access to. I populated a dict with math-related functions so you can easily provide access to those if you want, but you have to explicitly use it.
If the string attempts to call functions that haven't been provided, or invoke any methods, an exception will be raised, and it will not be executed.
Because this uses Python's built in parser and evaluator, it also inherits Python's precedence and promotion rules as well.
>>> evaluate("7 + 9 * (2 << 2)")
79
>>> evaluate("6 // 2 + 0.0")
3.0
The above code has only been tested on Python 3.
If desired, you can add a timeout decorator on this function.
I think I would use eval(), but would first check to make sure the string is a valid mathematical expression, as opposed to something malicious. You could use a regex for the validation.
eval() also takes additional arguments which you can use to restrict the namespace it operates in for greater security.
[I know this is an old question, but it is worth pointing out new useful solutions as they pop up]
Since python3.6, this capability is now built into the language, coined "f-strings".
See: PEP 498 -- Literal String Interpolation
For example (note the f prefix):
f'{2**4}'
=> '16'
Based on Perkins' amazing approach, I've updated and improved his "shortcut" for simple algebraic expressions (no functions or variables). Now it works on Python 3.6+ and avoids some pitfalls:
import re
# Kept outside simple_eval() just for performance
_re_simple_eval = re.compile(rb'd([\x00-\xFF]+)S\x00')
def simple_eval(expr):
try:
c = compile(expr, 'userinput', 'eval')
except SyntaxError:
raise ValueError(f"Malformed expression: {expr}")
m = _re_simple_eval.fullmatch(c.co_code)
if not m:
raise ValueError(f"Not a simple algebraic expression: {expr}")
try:
return c.co_consts[int.from_bytes(m.group(1), sys.byteorder)]
except IndexError:
raise ValueError(f"Expression not evaluated as constant: {expr}")
Testing, using some of the examples in other answers:
for expr, res in (
('2^4', 6 ),
('2**4', 16 ),
('1 + 2*3**(4^5) / (6 + -7)', -5.0 ),
('7 + 9 * (2 << 2)', 79 ),
('6 // 2 + 0.0', 3.0 ),
('2+3', 5 ),
('6+4/2*2', 10.0 ),
('3+2.45/8', 3.30625),
('3**3*3/3+3', 30.0 ),
):
result = simple_eval(expr)
ok = (result == res and type(result) == type(res))
print("{} {} = {}".format("OK!" if ok else "FAIL!", expr, result))
OK! 2^4 = 6
OK! 2**4 = 16
OK! 1 + 2*3**(4^5) / (6 + -7) = -5.0
OK! 7 + 9 * (2 << 2) = 79
OK! 6 // 2 + 0.0 = 3.0
OK! 2+3 = 5
OK! 6+4/2*2 = 10.0
OK! 3+2.45/8 = 3.30625
OK! 3**3*3/3+3 = 30.0
Testing bad input:
for expr in (
'foo bar',
'print("hi")',
'2*x',
'lambda: 10',
'2**1234',
):
try:
result = simple_eval(expr)
except ValueError as e:
print(e)
continue
print("OK!") # will never happen
Malformed expression: foo bar
Not a simple algebraic expression: print("hi")
Expression not evaluated as constant: 2*x
Expression not evaluated as constant: lambda: 10
Expression not evaluated as constant: 2**1234
This is a massively late reply, but I think useful for future reference. Rather than write your own math parser (although the pyparsing example above is great) you could use SymPy. I don't have a lot of experience with it, but it contains a much more powerful math engine than anyone is likely to write for a specific application and the basic expression evaluation is very easy:
>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> sympy.sympify("x**3 + sin(y)").evalf(subs={x:1, y:-3})
0.858879991940133
Very cool indeed! A from sympy import * brings in a lot more function support, such as trig functions, special functions, etc., but I've avoided that here to show what's coming from where.
Use eval in a clean namespace:
>>> ns = {'__builtins__': None}
>>> eval('2 ** 4', ns)
16
The clean namespace should prevent injection. For instance:
>>> eval('__builtins__.__import__("os").system("echo got through")', ns)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute '__import__'
Otherwise you would get:
>>> eval('__builtins__.__import__("os").system("echo got through")')
got through
0
You might want to give access to the math module:
>>> import math
>>> ns = vars(math).copy()
>>> ns['__builtins__'] = None
>>> eval('cos(pi/3)', ns)
0.50000000000000011
Here's my solution to the problem without using eval. Works with Python2 and Python3. It doesn't work with negative numbers.
$ python -m pytest test.py
test.py
from solution import Solutions
class SolutionsTestCase(unittest.TestCase):
def setUp(self):
self.solutions = Solutions()
def test_evaluate(self):
expressions = [
'2+3=5',
'6+4/2*2=10',
'3+2.45/8=3.30625',
'3**3*3/3+3=30',
'2^4=6'
]
results = [x.split('=')[1] for x in expressions]
for e in range(len(expressions)):
if '.' in results[e]:
results[e] = float(results[e])
else:
results[e] = int(results[e])
self.assertEqual(
results[e],
self.solutions.evaluate(expressions[e])
)
solution.py
class Solutions(object):
def evaluate(self, exp):
def format(res):
if '.' in res:
try:
res = float(res)
except ValueError:
pass
else:
try:
res = int(res)
except ValueError:
pass
return res
def splitter(item, op):
mul = item.split(op)
if len(mul) == 2:
for x in ['^', '*', '/', '+', '-']:
if x in mul[0]:
mul = [mul[0].split(x)[1], mul[1]]
if x in mul[1]:
mul = [mul[0], mul[1].split(x)[0]]
elif len(mul) > 2:
pass
else:
pass
for x in range(len(mul)):
mul[x] = format(mul[x])
return mul
exp = exp.replace(' ', '')
if '=' in exp:
res = exp.split('=')[1]
res = format(res)
exp = exp.replace('=%s' % res, '')
while '^' in exp:
if '^' in exp:
itm = splitter(exp, '^')
res = itm[0] ^ itm[1]
exp = exp.replace('%s^%s' % (str(itm[0]), str(itm[1])), str(res))
while '**' in exp:
if '**' in exp:
itm = splitter(exp, '**')
res = itm[0] ** itm[1]
exp = exp.replace('%s**%s' % (str(itm[0]), str(itm[1])), str(res))
while '/' in exp:
if '/' in exp:
itm = splitter(exp, '/')
res = itm[0] / itm[1]
exp = exp.replace('%s/%s' % (str(itm[0]), str(itm[1])), str(res))
while '*' in exp:
if '*' in exp:
itm = splitter(exp, '*')
res = itm[0] * itm[1]
exp = exp.replace('%s*%s' % (str(itm[0]), str(itm[1])), str(res))
while '+' in exp:
if '+' in exp:
itm = splitter(exp, '+')
res = itm[0] + itm[1]
exp = exp.replace('%s+%s' % (str(itm[0]), str(itm[1])), str(res))
while '-' in exp:
if '-' in exp:
itm = splitter(exp, '-')
res = itm[0] - itm[1]
exp = exp.replace('%s-%s' % (str(itm[0]), str(itm[1])), str(res))
return format(exp)
Using lark parser library https://stackoverflow.com/posts/67491514/edit
from operator import add, sub, mul, truediv, neg, pow
from lark import Lark, Transformer, v_args
calc_grammar = f"""
?start: sum
?sum: product
| sum "+" product -> {add.__name__}
| sum "-" product -> {sub.__name__}
?product: power
| product "*" power -> {mul.__name__}
| product "/" power -> {truediv.__name__}
?power: atom
| power "^" atom -> {pow.__name__}
?atom: NUMBER -> number
| "-" atom -> {neg.__name__}
| "(" sum ")"
%import common.NUMBER
%import common.WS_INLINE
%ignore WS_INLINE
"""
#v_args(inline=True)
class CalculateTree(Transformer):
add = add
sub = sub
neg = neg
mul = mul
truediv = truediv
pow = pow
number = float
calc_parser = Lark(calc_grammar, parser="lalr", transformer=CalculateTree())
calc = calc_parser.parse
def eval_expr(expression: str) -> float:
return calc(expression)
print(eval_expr("2^4"))
print(eval_expr("-1*2^4"))
print(eval_expr("-2^3 + 1"))
print(eval_expr("2**4")) # Error
I came here looking for a mathematic expression parser as well. Reading through some of the answers and looking up libraries, I came across py-expression which I am now using. It basically handles a lot of operators and formula constructs, but if you're missing something you can easily add new operators/functions to it.
The basic syntax is:
from py_expression.core import Exp
exp = Exp()
parsed_formula = exp.parse('a+4')
result = exp.eval(parsed_formula, {"a":2})
The only issue that I've had with it so far is that it doesn't come with built-in mathematical constants nor a mechanism to add them in. I just proposed a solution to that however: https://github.com/FlavioLionelRita/py-expression/issues/7

Resources