Conditionals stored as text to translate to real compares

R

Randall Parker

I want to know if there is some way to translate fragments of text into
operators (e.g. <, >, <>, ==, etc) to use in conditional expressions.

I've got a data structure which is a list of lists. A single list might
look like:

MyInnerList = ["MyVar",">",7]
or
MySecondInnerList = ["MyOtherVar","<=",25.5]

These all go in something like:
MyMainList = [["MyVar",">",7],["MyOtherVar","<=",25.5], and so on...]

I have some target device which I go query with the names in the first
field (e.g. "MyVar") to get values back. The target device returns all
values as strings. Then I want to compare to the value in the third
field.

In theory the third field might contain floats, integers, or maybe some
day strings.

So I access the middle operator field like this:

OperatorType = MyInnerList[1] # This gets back ">" or "<=" for example
TestVal = MyInnerList(2)
TargetVal gets filled in by talking to my target device.

Then I want to compare TestVal and TargetVal using OperatorType.

I'm thinking I have to do something like:

if OperatorType == ">":
# then do a greater than compare here.
BoolVal = TestVal > TargetVal
elif OperatorType == ">=":
# then do a greater or equal to here.
BoolVal = TestVal >= TargetVal
and so on.

It would seem a lot easier to do:

BoolVal = TargetVal EvalStrToOper(">") MyInnerList(2)

where EvalStrToOper creates an immediate > sign that then allows that
line to get evaluated by the interpreter.

Is there any way to do that in Python?

Of course, I'd have to guarantee that the ">" or other operators are
really legal operators. Also, I'd have to test MyInnerList(2) to make
sure it is an appropriate type.
 
M

Mike Meyer

Randall Parker said:
if OperatorType == ">":
# then do a greater than compare here.
BoolVal = TestVal > TargetVal
elif OperatorType == ">=":
# then do a greater or equal to here.
BoolVal = TestVal >= TargetVal
and so on.

It would seem a lot easier to do:

BoolVal = TargetVal EvalStrToOper(">") MyInnerList(2)

where EvalStrToOper creates an immediate > sign that then allows that
line to get evaluated by the interpreter.


How about:

BoolVal = EvalStrToOper[">"](TargetVal, MyInnerList(2)) ?

EvalStrOper = {'>': operator.gt, '>=': operator.ge,
'<': operator.lt, '<=': operator.le,
...

<mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top