File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1313)
1414import ast
1515import operator
16+ import math
1617import asyncio
1718import time
1819from typing import Optional
@@ -273,6 +274,36 @@ def safe_eval(self, expr):
273274 ast .USub : operator .neg
274275 }
275276
277+ constants = {
278+ "e" : math .e ,
279+ "pi" : math .pi ,
280+ "tau" : math .tau ,
281+ }
282+
283+ functions = {
284+ "log" : math .log ,
285+ "log10" : math .log10 ,
286+ "sqrt" : math .sqrt ,
287+ "factorial" : math .factorial ,
288+ "ceil" : math .ceil ,
289+ "floor" : math .floor ,
290+ "trunc" : math .trunc ,
291+ "sin" : math .sin ,
292+ "cos" : math .cos ,
293+ "tan" : math .tan ,
294+ "asin" : math .asin ,
295+ "acos" : math .acos
296+ "atan" : math .atan ,
297+ "degrees" : math .degrees ,
298+ "radians" : math .radians ,
299+ "sinh" : math .sinh ,
300+ "cosh" : math .cosh ,
301+ "tanh" : math .tanh ,
302+ "asinh" : math .asinh ,
303+ "acosh" : math .acosh ,
304+ "atanh" : math .atanh ,
305+ }
306+
276307 def eval_node (node ):
277308 if isinstance (node , ast .Constant ):
278309 if isinstance (node .value , (int , float )):
@@ -291,6 +322,16 @@ def eval_node(node):
291322 op = type (node .op )
292323 if op in operators :
293324 return operators [op ](eval_node (node .operand ))
325+ elif isinstance (node , ast .Call ):
326+ if isinstance (node .func , ast .Name ):
327+ if node .func .id in functions :
328+ args = [eval_node (a ) for a in node .args ]
329+ return functions [node .func .id ](* args )
330+
331+ elif isinstance (node , ast .Name ):
332+ if node .id in constants :
333+ return constants [node .id ]
334+ raise TypeError (f"Unknown identifier { node .id } " )
294335 raise TypeError ("Unsupported type" )
295336
296337 try :
You can’t perform that action at this time.
0 commit comments