operators from strings?

Is there a way to convert operators from strings? I’m doing a big overhaul of my dialogue/quest system and making it more robust, but I am having trouble finding anything on this…the more research I do the more I just see string comparison but nothing in regards to converting strings to operators…

for example I return a list from a txt, ini whatever into a list called…we’ll say lines[].
I have a string line[0] that I split into it’s own list I’ll call it compare…
so…
compare = line[0].split(’:’)
It returns [gameObject,property,operator,value]…by operator I mean comparison… >,<, != etc…

is this possible to do simply? or do I need to just get stupid and roll my own hacky solution? by hacky I do not mean buggy…I just mean not optimized or pythonic(so to say)…like assigning a number and doing a lookup with a switch…but this could get messy.

I do understand the security risks.

EDIT: I think I have found something…finally I stumbled upon the operator lib…now I just need to see if I can get it to work.

You can address the operators using the getattribute function and some magic names (you can use dir(obj) to see what they all are). This means if you have a dict mapping symbols to these magic names, and then a call to getattribute to retrieve the function, you can do it in quite a small amount of code:


OPERATORS = {
    '=': '__eq__', 
    '!=': '__ne__', 
    '+': '__add__',
    '-': '__sub__',
    '&gt;': '__gt__', # I may have this the wrong way around.
    ....
}


...
operand_a = &lt;the thing you are operating on&gt;
operand_b = &lt;the other thing you are operating with&gt;
str_operator = &lt;something like +, &gt; != etc &gt;
result = operand_a.__getattribute__(OPERATORS[str_operator])(operand_b)

So it could be:


prop_val = gameObject[property]
new_prop_val = prop_val.__getattribute__(OPERATORS[operator])(value)
gameObject[property] = new_prop_val

Thanks,I managed to get it working…but I did not define a dict…I simply assign them based on a string value in a small function from reading and parsing the text file…the script only triggers once during a key press(action button for speaking to characters and if I click on a button) so it’s a little longer(more lines) but it is simpler to read for others or me…which helps if I have to come back to it…again ugh! :slight_smile: