Package dap :: Package util :: Module safeeval
[hide private]
[frames] | no frames]

Module safeeval

source code

Functions [hide private]
  _get_opcodes(codeobj)
Extract the actual opcodes as a list from a code object
  test_expr(expr)
Test that the expression contains only the listed opcodes.
  const_eval(expression)
Safe Python constant evaluation
  expr_eval(expression)
Safe Python expression evaluation

Variables [hide private]
  _const_codes = [1, 2, 3, 5, 4, 103, 104, 102, 100, 83, 60]
  _expr_codes = [1, 2, 3, 5, 4, 103, 104, 102, 100, 83, 60, 10, 11, ...

Imports: dis


Function Details [hide private]

_get_opcodes(codeobj)

source code 
Extract the actual opcodes as a list from a code object
>>> c = compile("[1 + 2, (1,2)]", "", "eval")
>>> _get_opcodes(c)
[100, 100, 23, 100, 100, 102, 103, 83]
Returns:
[opcodes]

test_expr(expr)

source code 
Test that the expression contains only the listed opcodes. If the expression is valid and contains only allowed codes, return the compiled code object. Otherwise raise a ValueError
Returns:
codeobj

const_eval(expression)

source code 

Safe Python constant evaluation

Evaluates a string that contains an expression describing a Python constant. Strings that are not valid Python expressions or that contain other code besides the constant raise ValueError.
>>> const_eval("10")
10
>>> const_eval("[1,2, (3,4), {'foo':'bar'}]")
[1, 2, (3, 4), {'foo': 'bar'}]
>>> const_eval("1+2")
Traceback (most recent call last):
...
ValueError: opcode BINARY_ADD not allowed
Returns:
value

expr_eval(expression)

source code 

Safe Python expression evaluation

Evaluates a string that contains an expression that only uses Python constants. This can be used to e.g. evaluate a numerical expression from an untrusted source.
>>> expr_eval("1+2")
3
>>> expr_eval("[1,2]*2")
[1, 2, 1, 2]
>>> expr_eval("__import__('sys').modules")
Traceback (most recent call last):
...
ValueError: opcode LOAD_NAME not allowed
Returns:
value


Variables Details [hide private]

_const_codes

None
Value:
[1, 2, 3, 5, 4, 103, 104, 102, 100, 83, 60]                            
      

_expr_codes

None
Value:
[1, 2, 3, 5, 4, 103, 104, 102, 100]