Alternative to 'eval'

As you’ve noticed - eval is not available for client side python.

For some security issues I don’ think it’s recommended to do eval for javascript but as a class project to do some maths I can’t see it being a problem.

Here’s two alternatives for eval on the client and both should work for simple maths expressions which don’t rely on variables so

x = eval('1+2') # will work
y = eval('x+1') # won't work

https://anvil.works/build#clone:XWTARROOTTB5EJBS=A76XRDZV7PSJYJ7DQA3OOBGT

The first does the eval on the server

@anvil.server.callable
def eval_expression(expr):
  return eval(expr)

The second does a simple js_call and runs javascripts eval function

function eval_expression(expr) {
  return eval(expr)
}

Then on the client you can do:

eval = lambda expr: anvil.server.call('eval_expression', expr)
# or
eval = lambda expr: js.call_js('eval_expression', expr)

2 Likes