pysys.utils.safeeval

Contains the safeEval function.

safeEval

pysys.utils.safeeval.safeEval(expr, errorMessage='Failed to evaluate "{expr}" due to {error}', emptyNamespace=False, extraNamespace={})[source]

Executes eval(…) on the specified string expression, using a controlled globals()/locals() environment to ensure we do not break compatibility between PySys versions, and that a sensible set of PySys constants and modules are available.

Unless emptyNamespace=True, the global environment used for evaluation includes the os.path, math, sys, re, json, and locale standard Python modules, as well as the pysys module and the contents of the pysys.constants module, e.g. IS_WINDOWS.

If necessary, symbols for additional modules can be imported dynamically using import_module:

x = safeEval("import_module('difflib').get_close_matches('app', ['apple', 'orange', 'applic']")

If an error occurs, an exception is raised that includes the expression in its message.

Parameters
  • expr (str) – The string to be evaluated.

  • errorMessage (str) – The string used for the raised exception message if an exception is thrown by eval, where {expr} will be replaced with the actual expression and {error} with the error message.

  • emptyNamespace (bool) – By default a default namespace is provided including the symbols described above such as os.path, pysys, etc. Set this to True to start with a completely empty namespace with no symbols defined.

  • extraNamespace (dict[str,obj]) – A dict of string names and Python object values to be included in the globals environment used to evaluate this string.

New in version 2.0.