Conditionals stored as text to translate to real compares

Randall Parker techiepundit at futurepundit.com
Thu Jan 12 19:03:20 EST 2006


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.




More information about the Python-list mailing list