Alexander Borochkin
Alexander Borochkin

Reputation: 4641

Correct syntax for "if" expression in simpleeval (Simple Eval)

I try to use simpleeval library to evaluate some expressions from user text input. Here is code example.

!pip install simpleeval

from simpleeval import EvalWithCompoundTypes

COMPOUND_TYPES_NAMES = {
    'null': None,
    "true": True,
    "false": False
}
block = "set_value('user_city', get_slot('city_entity'), 'unknown') if get_slot('city_entity')"

def get_slot(slot: str) -> str:
    return None

def set_value(var_name: str, var_value: str, context: str):
    print(var_name, var_value)

EvalWithCompoundTypes(
    functions={
        "get_slot": lambda slot: get_slot(slot),
        'set_value': lambda var_name, var_value, context: set_value(var_name, var_value, context)
    },
    names=COMPOUND_TYPES_NAMES).eval(block)

In the example above when evaluating the expression defined in the string variable the following mistake occurred:

set_value('user_city', get_slot('city_entity'), 'unknown') if get_slot('city_entity')
                                                                                        ^
SyntaxError: invalid syntax

What is the correct syntax for the expression above?

Upvotes: 0

Views: 394

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295687

This problem isn't specific to SimpleEval. expression if condition isn't valid syntax in general, and you can validate this using the standard-library function ast.parse() (which is what SimpleEval is doing under the hood).

Consider condition and expression, or expression if condition else None.

Upvotes: 2

Related Questions