1

I'd like to substitute a comparison marker based on the context of a string. I'm doing it in part with a PyQt5 experiment on Python 3.5.

For example:

line = "<"

if 1 line 2:
    print("False")

Is there any easy way to do this? I considered using a test case as such:

if line == "<":
    if 1 < 2:
        print("False")

etc, etc, but this gets long, especially with iterative "if" statements. Ex.:

if pt1 < pt1_target:
    if pt2 > pt2_target:
        etc.

Or if this is not possible, does anyone have any solution to avoid a massive, catch-all "if" statement block for each branch? I plan on putting a little instruction in so line ends up substituting for the correct python equivalent, such as "=" instead of the correct "==".

Thanks in advance!

MadisonCooper
  • 236
  • 2
  • 15
  • 1
    Check also [How to pass an operator to a python function?](http://stackoverflow.com/questions/18591778/how-to-pass-an-operator-to-a-python-function), [assign operator to variable in python?](http://stackoverflow.com/questions/2983139/assign-operator-to-variable-in-python) – user2314737 Oct 31 '16 at 21:31

2 Answers2

3

Use the functions from the operator module:

from operator import eq, ne, lt, le, gt, ge

operator_functions = {
    '=': eq,
    '!=': ne,
    '<': lt,
    '<=': le,
    '>': gt,
    '>=': ge,
}

operator = # whatever

if operator_functions[operator](a, b):
    do_whatever()
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Is that `'=': eq` on purpuse, to say that those do not have to conform to standard Python operator syntax? – tobias_k Oct 31 '16 at 21:29
  • 1
    @tobias_k: That was deliberate, since it sounded from the question like the input would be using `=` instead of `==`. I probably should have put in a comment or something about that. – user2357112 Oct 31 '16 at 21:31
  • @user2357112 I like that I don't have to add instructions for what the operator needs to look like, the natural "=" works. Thanks! – MadisonCooper Oct 31 '16 at 21:35
  • 1
    if you're worried about variations in input you can put both `'=': eq, '==': eq, ...`. – Pyrce Oct 31 '16 at 21:36
2

You can use a dictionary to map the operator string to the corresponding function in the operator module:

import operator

ops = {'>': operator.gt,
       '<': operator.lt,
       '==': operator.eq,
       # etc...
      }

op_string = '<'
if ops[op_string](1, 2):
    print('True')
# or this...
print(ops[op_string](1, 2))

Note that this example prints True. Your example seemed to negate the logic such that 1 < 2 would evaluate to False - if that's what you want then you can switch around the logic:

if ops[op_string](1, 2):
    print 'False'
# or this...
print(not ops[op_string](1, 2))

Or you could change the operator mapping:

ops = {'<': operator.ge, ...}
print(ops[op_string](1, 2))
# False
mhawke
  • 84,695
  • 9
  • 117
  • 138