Safely evaluate an arithmetic expression. :param s: expression to evaluate; should only contain numbers, spaces, or the symbols `+, -, *, /, _, (, )`; exponential notation is supported :param max_len: maximum length string that will be evaluated; longer strings raise a `Valu
(s: str, max_len: int = 1024)
| 9 | |
| 10 | |
| 11 | def _safe_eval(s: str, max_len: int = 1024) -> Union[int, float]: |
| 12 | """Safely evaluate an arithmetic expression. |
| 13 | |
| 14 | :param s: expression to evaluate; should only contain numbers, spaces, or the |
| 15 | symbols `+, -, *, /, _, (, )`; exponential notation is supported |
| 16 | :param max_len: maximum length string that will be evaluated; longer strings raise |
| 17 | a `ValueError` |
| 18 | """ |
| 19 | # XXX need to be smarter about this |
| 20 | is_safe = all(ch in "e0123456789_+-*/(). " for ch in s) |
| 21 | if not is_safe: |
| 22 | raise ValueError( |
| 23 | "Only simple arithmetic expressions involving digits, parentheses, " |
| 24 | "the letter e, or the symbols '+-*/_.' are allowed" |
| 25 | ) |
| 26 | if len(s) > max_len: |
| 27 | raise ValueError(f"String length is {len(s)}, maximum allowed is {max_len}") |
| 28 | return eval(s) |
| 29 | |
| 30 | |
| 31 | # allow for the ${eval:...} resolver in the config file to perform simple arithmetic |
nothing calls this directly
no outgoing calls
no test coverage detected