7

Unlike the eval function, ast.literal_eval function safely evaluates an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
I.e. It only evaluates the strings containing literal or containers, it does not evaluate the strings containing code!

I am wondering if there is an equivalent of the literal_eval method in R? Thanks in advance!

Reference: ast.literal_eval function

anilbey
  • 1,817
  • 4
  • 22
  • 38

1 Answers1

0

The answer to safely evaluating arithmetic expressions allows to create a function resembling ast.literal_eval for string input.
This function takes as arguments the input string to evaluate, as well as the allowed operations, with default values similar to what ast.literal_eval allows :

literal_eval <- function(input, allowed = c("list", "c", "+", "-", "/", "*")) {
  # Create safe empty environment
  safe_env <- new.env(parent = emptyenv())
  
  # assign allowed functions
  lapply(allowed,function(f) assign(f,get(f, "package:base"),safe_env))

  # Evaluate input
  safe_env$expr <- parse(text = input)
  eval(substitute(expr,env = safe_env), env = safe_env)
}

literal_eval("1+1")
[1] 2

literal_eval("c(1,2)")
[1] 1 2

literal_eval("list(2,3)")
[[1]]
[1] 2

[[2]]
[1] 3

literal_eval("system('delete *.*')")
 Error in system('delete *.*') : unknown function "system" 

Waldi
  • 39,242
  • 6
  • 30
  • 78