0

I need to bring == from json to compare s1==s2 in python file instead of directly assign the comparison operator I need to get it from json

def something():
    s1=“Search_string”
    s2=“searchstring”
    if s1 == s2:
        print("Success")
    else:
        print(“Error”)

json:

{
    "Mapping": 
        {
            "Operator": "=="
        } 
}
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
Joji k joy
  • 33
  • 9
  • This isn’t a regex solution and not sure if you can do this, but you can probably keep a dictionary with the operator string (i.e. “==“) as the key and the operator itself (operator.eq) as the value, then pass the value from the json as the key of the dictionary, thus returning your operator – koolahman Aug 03 '19 at 11:37

1 Answers1

0

You can use compiledocs and evaldocs:

def something(s1, s2, op="=="):
    # if using an older python version which doesn't supports f-string
    # use something like `format` to put the `op` variable in the string.
    if eval(compile(f"bool(s1 {op} s2)", "<string>", "eval")):
        print("Success")
    else:
        print("Error")


s1 = "Search_string"
s2 = "searchstring"
op = "=="  # load the actual string from your json, this is just for demo
something(s1, s2, op)  # prints Error
something(s1, s2, "!=")  # prints Success
something(s1, s1, op)  # prints Success

Load the operator string from your json file, I hope you know how to do that.
For more info on eval and compile see this SO answer, very thorough, no point of me trying to explain them here.

Warning: Beware code like this can be dangerous if you don't have control over whats coming from the json file. Someone can insert any random code in your python script just by editing the json file.

Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48