Package: simpleeval
A single file library for easily adding evaluatable expressions into
python projects.  Say you want to allow a user to set an alarm volume, which
could depend on the time of day, alarm level, how many previous alarms had gone
off, and if there is music playing at the time.Or if you want to allow simple formulae in a web application, but don’t want to
give full eval() access, or don’t want to run in javascript on the client side.It’s deliberately trying to stay simple to use and not have millions of features,
pull it in from PyPI (pip or easy_install), or even just a single file you can dump
into a project.Internally, it’s using the amazing pythonastmodule to parse the
expression, which allows very fine control of what is and isn’t allowed.  It
should be completely safe in terms of what operations can be performed by the
expression.The only issue I know to be aware of is that you can create an expression which
takes a long time to evaluate, or which evaluating requires an awful lot of
memory, which leaves the potential for DOS attacks.  There is basic protection
against this, and you can lock it down further if you desire. (see theOperatorssection below)You should be aware of this when deploying in a public setting.The defaults are pretty locked down and basic, and it’s easy to add
whatever extra specific functionality you need (your own functions,
variable/name lookup, etc).Basic UsageTo get very simple evaluating:fromsimpleevalimportsimple_evalsimple_eval("21 + 21")returns42.Expressions can be as complex and convoluted as you want:simple_eval("21 + 19 / 7 + (8 % 3) ** 9")returns535.714285714.You can add your own functions in as well.simple_eval("square(11)",functions={"square":lambdax:x*x})returns121.For more details of working with functions, read further down.Note:all further examples use>>>to designate python code, as if you are using
the python interactive prompt.OperatorsYou can add operators yourself, using theoperatorsargument, but these are
the defaults:+add two things.x + y1 + 1->2-subtract two thingsx - y100 - 1->99/divide one thing by anotherx / y100/10->10*multiple one thing by anotherx * y10 * 10->100**‘to the power of’x**y2 ** 10->1024%modulus. (remainder)x % y15 % 4->3==equalsx == y15 == 4->False<Less than.x < y1 < 4->True>Greater than.x > y1 > 4->False<=Less than or Equal to.x <= y1 < 4->True>=Greater or Equal tox >= 211 >= 4->False>>“Right shift” the number.100 >> 2->25<<“Left shift” the number.100 << 2->400inis something contained within
something else."spam" in "my breakfast"->False^“bitwise exclusive OR” (xor)62 ^ 20->42|“bitwise OR”8 | 34->42&“bitwise AND”100 & 63->36~“bitwise invert”~-43->42The^operator is often mistaken for a exponent operator, not the bitwise
operation that it is in python, so if you want3 ^ 2to equal9, you can
replace the operator like this:>>>importast>>>fromsimpleevalimportsafe_power>>>s=SimpleEval()>>>s.operators[ast.BitXor]=safe_power>>>s.eval("3 ^ 2")9for example.Limited PowerAlso note, the**operator has been locked down by default to have a
maximum input value of4000000, which makes it somewhat harder to make
expressions which go on for ever.  You can change this limit by changing thesimpleeval.POWER_MAXmodule level value to whatever is an appropriate value
for you (and the hardware that you’re running on) or if you want to completely
remove all limitations, you can set thes.operators[ast.Pow] = operator.powor make your own function.On my computer,9**9**5evaluates almost instantly, but9**9**6takes
over 30 seconds.  Since9**7is4782969, and so over thePOWER_MAXlimit, it throws aNumberTooHighexception for you. (Otherwise it would go
on for hours, or until the computer runs out of memory)Strings (and other Iterables) SafetyThere are also limits on string length (100000 characters,MAX_STRING_LENGTH).  This can be changed if you wish.Related to this, if you try to create a silly long string/bytes/list, by doing'i want to breakfree'.split()* 9999999999for instance, it will block you.If ExpressionsYou can use python styleif x then y else ztype expressions:>>>simple_eval("'equal' if x == y else 'not equal'",names={"x":1,"y":2})'not equal'which, of course, can be nested:>>>simple_eval("'a' if 1 == 2 else 'b' if 2 == 3 else 'c'")'c'FunctionsYou can define functions which you’d like the expresssions to have access to:>>>simple_eval("double(21)",functions={"double":lambdax:x*2})42You can define “real” functions to pass in rather than lambdas, of course too,
and even re-name them so that expressions can be shorter>>>defdouble(x):returnx*2>>>simple_eval("d(100) + double(1)",functions={"d":double,"double":double})202If you don’t provide your ownfunctionsdict, then the the following defaults
are provided in theDEFAULT_FUNCTIONSdict:randint(x)Return a randomintbelowxrand()Return a randomfloatbetween 0 and 1int(x)Convertxto anint.float(x)Convertxto afloat.str(x)Convertxto astr(unicodein py2)If you want to provide a list of functions, but want to keep these as well,
then you can do a normal python.copy()&.update:>>>my_functions=simpleeval.DEFAULT_FUNCTIONS.copy()>>>my_functions.update(square=(lambdax:x*x),double=(lambdax:x+x),)>>>simple_eval('square(randint(100))',functions=my_functions)NamesSometimes it’s useful to have variables available, which in python terminology
are called ‘names’.>>>simple_eval("a + b",names={"a":11,"b":100})111You can also hand the handling of names over to a function, if you prefer:>>>defname_handler(node):returnord(node.id[0].lower(a))-96>>>simple_eval('a + b',names=name_handler)3That was a bit of a silly example, but you could use this for pulling values
from a database or file, say, or doing some kind of caching system.The two default names that are provided areTrueandFalse.  So if you want to provide your own names, but wantTrueandFalseto keep working, either provide them yourself, or.copy()and.updatetheDEFAULT_NAMES. (See functions example above).Creating an Evaluator ClassRather than creating a new evaluator each time, if you are doing a lot of
evaluations, you can create a SimpleEval object, and pass it expressions each
time (which should be a bit quicker, and certainly more convenient for some use
cases):>>>s=SimpleEval()>>>s.eval("1 + 1")2>>>s.eval('100 * 10')1000# and so on...One useful feature of using theSimpleEvalobject is that you can parse an expression
once, and then evaluate it mulitple times using differentnames:# Set up & Cache the parse tree:expression="foo + bar"parsed=s.parse(expression)# evaluate the expression multiple times:fornamesin[{"foo":1,"bar":10},{"foo":100,"bar":42}]:s.names=namesprint(s.eval(expression,previously_parsed=parsed))for instance.  This may help with performance.You can assign / edit the various options of theSimpleEvalobject if you
want to.  Either assign them during creation (like thesimple_evalfunction)defboo():return'Boo!'s=SimpleEval(functions={"boo":boo})or edit them after creation:s.names['fortytwo']=42this actually means you can modify names (or functions) with functions, if you
really feel so inclined:s=SimpleEval()defset_val(name,value):s.names[name.value]=value.valuereturnvalue.values.functions={'set':set_val}s.eval("set('age', 111)")Say.  This would allow a certain level of ‘scriptyness’ if you had these
evaluations happening as callbacks in a program.  Although you really are
reaching the end of what this library is intended for at this stage.Compound TypesCompound types (dict,tuple,list,set) in general just work if
you pass them in as named objects.  If you want to allow creation of these, theEvalWithCompoundTypesclass works.  Just replace any use ofSimpleEvalwith
that.TheEvalWithCompoundTypesclass also contains support for simple comprehensions.
eg:[x + 1 for x in [1,2,3]].  There’s a safetyMAX_COMPREHENSION_LENGTHto control
how many items it’ll allow before bailing too.  This also takes into account nested
comprehensions.Since the primary intention of this library is short expressions - an extra ‘sweetener’ is
enabled by default.  You can access a dict (or similar’s) keys using the .attr syntax:>>>simple_eval("foo.bar",names={"foo":{"bar":42}})42for instance.  You can turn this off either by setting the module globalATTR_INDEX_FALLBACKtoFalse, or on theSimpleEvalinstance itself. e.g.evaller.ATTR_INDEX_FALLBACK=False.ExtendingTheSimpleEvalclass is pretty easy to extend.  For instance, to create a
version that disallows method invocation on objects:importastimportsimpleevalclassEvalNoMethods(simpleeval.SimpleEval):def_eval_call(self,node):ifisinstance(node.func,ast.Attribute):raisesimpleeval.FeatureNotAvailable("No methods please, we're British")returnsuper(EvalNoMethods,self)._eval_call(node)and then useEvalNoMethodsinstead of theSimpleEvalclass.Other…The library supports python 3 - but should be mostly compatible (and tested before 0.9.11)
with python 2.7 as well.Object attributes that start with_orfunc_are disallowed by default.
If you really need that (BE CAREFUL!), then modify the module globalsimpleeval.DISALLOW_PREFIXES.A few builtin functions are listed insimpleeval.DISALLOW_FUNCTIONS.type,open, etc.
If you need to give access to this kind of functionality to your expressions, then be very
careful.  You’d be better wrapping the functions in your own safe wrappers.The initial idea came from J.F. Sebastian on Stack Overflow
(http://stackoverflow.com/a/9558001/1973500) with modifications and many improvements,
see the head of the main file for contributors list.Please read thetest_simpleeval.pyfile for other potential gotchas or
details.  I’m very happy to accept pull requests, suggestions, or other issues.
Enjoy!DevelopingRun tests:$ make testOr to set the tests running on every file change:$ make autotest(requiresentr)I’m trying to keep the codebase relatively clean with Black, isort, pylint & mypy.
See:$ make formatand:$ make lintBEWAREI’ve done the best I can with this library - but there’s no warranty, no guarantee, nada.  A lot of
very clever people think the whole idea of trying to sandbox CPython is impossible.  Read the code
yourself, and use it at your own risk.