ae.dynamicod
dynamic execution of code blocks and expressions
this ae namespace portion provides useful helper functions to evaluate Python expressions and execute Python code dynamically at application run-time.
dynamically executed code block or expression string offers convenience for powerful system and application configuration and for data-driven architectures.
for the dynamic execution of functions and code blocks the helper functions try_call()
, try_exec()
and exec_with_return()
are provided. the helper function try_eval()
evaluates dynamic expressions.
Note
security considerations
make sure that any dynamically executed code is from a secure source to prevent code injections of malware. treat configuration files from untrusted sources with extreme caution and only execute them after a complete check and/or within a sandbox.
Hint
these functions are e.g. used by the Literal
class to dynamically determine literal values.
Module Attributes
default if no global variables get passed in dynamic code/expression evaluations |
Functions
|
execute python code block and return the resulting value of its last code line. |
|
execute callable while ignoring specified exceptions and return callable return value. |
|
evaluate expression string ignoring specified exceptions and return evaluated value. |
|
execute python code block string ignoring specified exceptions and return value of last code line in block. |
- exec_with_return(code_block, ignored_exceptions=(), glo_vars=None, loc_vars=None)[source]
execute python code block and return the resulting value of its last code line.
- Parameters:
- Return type:
- Returns:
value of the expression at the last code line or UNSET if either code block is empty, only contains comment lines, or one of the ignorable exceptions raised or if last code line is no expression.
inspired by this SO answer https://stackoverflow.com/questions/33409207/how-to-return-value-from-exec-in-function/52361938#52361938.
- try_call(callee, *args, ignored_exceptions=(), **kwargs)[source]
execute callable while ignoring specified exceptions and return callable return value.
- Parameters:
- Return type:
- Returns:
function return value or UNSET if an ignored exception got thrown.
- try_eval(expr, ignored_exceptions=(), glo_vars=None, loc_vars=None)[source]
evaluate expression string ignoring specified exceptions and return evaluated value.
- Parameters:
- Return type:
- Returns:
function return value or UNSET if an ignored exception got thrown.
- try_exec(code_block, ignored_exceptions=(), glo_vars=None, loc_vars=None)[source]
execute python code block string ignoring specified exceptions and return value of last code line in block.
- Parameters:
- Return type:
- Returns:
function return value or UNSET if an ignored exception got thrown.
- base_globals
default if no global variables get passed in dynamic code/expression evaluations