Hi,
the following will check the input and make it safe to use. Lets user use all functions in `math` module as well as `natural` expression.
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('del exp') == None
True
Comment
Thanks! Every little helps.
Parent comment
Hi, the following will check the input and make it safe to use. Lets user use all functions in `math` module as well as `natural` expression. 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('del exp') == None True