1.6.251. numpy.safe_eval

numpy.safe_eval(source)[source]

Protected string evaluation.

Evaluate a string containing a Python literal expression without allowing the execution of arbitrary non-literal code.

Parameters:

source : str

The string to evaluate.

Returns:

obj : object

The result of evaluating source.

Raises:

SyntaxError

If the code has invalid Python syntax, or if it contains non-literal code.

Examples

>>> np.safe_eval('1')
1
>>> np.safe_eval('[1, 2, 3]')
[1, 2, 3]
>>> np.safe_eval('{"foo": ("bar", 10.0)}')
{'foo': ('bar', 10.0)}
>>> np.safe_eval('import os')
Traceback (most recent call last):
  ...
SyntaxError: invalid syntax
>>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
Traceback (most recent call last):
  ...
SyntaxError: Unsupported source construct: compiler.ast.CallFunc