kwcoco.util.util_eval module

Defines a safer eval function

exception kwcoco.util.util_eval.RestrictedSyntaxError[source]

Bases: Exception

An exception raised by restricted_eval if a disallowed expression is given

kwcoco.util.util_eval.restricted_eval(expr, max_chars=32, local_dict=None, builtins_passlist=None)[source]

A restricted form of Python’s eval that is meant to be slightly safer

Parameters:
  • expr (str) – the expression to evaluate

  • max_char (int) – expression cannot be more than this many characters

  • local_dict (Dict[str, Any]) – a list of variables allowed to be used

  • builtins_passlist (List[str] | None) – if specified, only allow use of certain builtins

References

https://realpython.com/python-eval-function/#minimizing-the-security-issues-of-eval

Notes

This function may not be safe, but it has as many mitigation measures that I know about. This function should be audited and possibly made even more restricted. The idea is that this should just be used to evaluate numeric expressions.

Example

>>> from kwcoco.util.util_eval import *  # NOQA
>>> builtins_passlist = ['min', 'max', 'round', 'sum']
>>> local_dict = {}
>>> max_chars = 32
>>> expr = 'max(3 + 2, 9)'
>>> result = restricted_eval(expr, max_chars, local_dict, builtins_passlist)
>>> expr = '3 + 2'
>>> result = restricted_eval(expr, max_chars, local_dict, builtins_passlist)
>>> expr = '3 + 2'
>>> result = restricted_eval(expr, max_chars)
>>> import pytest
>>> with pytest.raises(RestrictedSyntaxError):
>>>     expr = 'max(a + 2, 3)'
>>>     result = restricted_eval(expr, max_chars, dict(a=3))