ChildishJack ChildishJack - 1 year ago 122
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:

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

if line == "<":
if 1 < 2:

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

if pt1 < pt1_target:
if pt2 > pt2_target:

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
ends up substituting for the correct python equivalent, such as
instead of the correct

Thanks in advance!

Answer Source

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):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download