ChildishJack ChildishJack - 1 month ago 23
Python Question

Python Comparison Evaluator Substitution

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!

Answer

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()