safe

exception lib.safe.UnsafeError
Bases: exceptions.Exception
lib.safe.assert_safe(expr, _globals=None, _locals=None, validate=None)
lib.safe.assert_safe_expr(meta_expr, _globals=None, _locals=None, validate=None, preprocess=<function <lambda> at 0x26a9398>)
lib.safe.compile_expr(meta_expr, _globals=None, _locals=None, validate=None, preprocess=<function <lambda> at 0x26a92a8>, safe=True)

If safe is a list, a restricted evaluation will be executed. Otherwise if safe is None, a unrestriced eval will be executed.

Parameters:
  • meta_expr (string) – meta-expression with <subexpressions>
  • _globals (dict) – globals
  • _locals (dict) – locals
  • safe (list or None) – safe names which will be accepted by the compiler
  • preprocess (callable) – preprocess expression (e.g. for ## formatting)
>>> compile_expr('<1+1>_<abs(2-3)>', safe=False)
u'2_1'
>>> compile_expr('<###(index+1)>', _locals={'index':1},
...     preprocess=format_expr, safe=False)
u'002'
lib.safe.eval_restricted(s, _globals=None, _locals=None, allowed=[, 'abs', 'int', 'min', 'max', 'pow', 'sum', 'True', 'False', 'denominator', 'numerator', 'chr', 'lower', 'str', 'title', 'upper', 'day', 'hour', 'microsecond', 'minute', 'month', 'monthname', 'second', 'weekday', 'weekdayname', 'year'])

Evaluate an expression while allowing a restricted set of names.

Parameter:allowed (list of string) – allowed names
Returns:result
>>> eval_restricted('max(a, a+b)', _globals={'a':0, 'b':2},
... _locals={'a':1}, allowed=['max'])
3
>>> try:
...     eval_restricted('a+b+c', _globals={'a':0, 'b':2}, _locals={'a':1})
... except UnsafeError, error:
...     print(error)
The following name(s) are invalid: c
lib.safe.eval_safe(expr, _globals=None, _locals=None, validate=None)

Safely evaluate an expression. It will raise a ValueError if non validated names are used.

Parameter:expr (string) – expression
Returns:result
>>> eval_safe('1+1')
2
>>> try:
...     eval_safe('"lowercase".upper()')
... except UnsafeError, error:
...     print(error)
The following name(s) are invalid: upper
lib.safe.extend_vars(vars, s)

Extend vars with new unique variables from s.

Parameters:
  • vars (list of string) – collection of previous variables
  • s (string) – multiple expressions
>>> vars = ['a1']
>>> extend_vars(vars, '<a1>_<foo>_<world>_<###index>')
>>> vars
['a1', 'foo', 'world', 'index']
lib.safe.format_expr(s)

Returns an expression with #### in a pure python expression which can be evaluated.

Parameter:s (expression) – expression
>>> f = format_expr('###(5+1)')
>>> f
'"%03d"%(5+1)'
>>> eval(f)
'006'

Previous topic

reverse_translation

Next topic

system