[Tutor] Is there a way to store and later use comparison operators (<, <=, =, >=, >) ?
boB Stepp
robertvstepp at gmail.com
Thu Apr 30 05:57:26 CEST 2015
On Wed, Apr 29, 2015 at 5:49 PM, Peter Otten <__peter__ at web.de> wrote:
> boB Stepp wrote:
>> So I have stumbled (With your gracious help!) into a legitimate use of
>> eval()?
>
> No. To expand on Marks hint here's how to do it without evil eval().
>
> import operator
>
> comps = {
> "=": operator.eq,
> "<": operator.lt,
> ">": operator.gt,
> # ...
> }
>
> def choose_compare(operator, value0, value1, pass_color, fail_color):
> op = comps[operator]
> if op(value0, value1):
> return pass_color, True
> else:
> return fail_color, False
>
> print(choose_compare("=", 1, 1, "red", "blue"))
> print(choose_compare("<", 1, 2, "red", "blue"))
> print(choose_compare("<", 2, 1, "red", "blue"))
>
> Rule of thumb: when you think you need eval() you're wrong.
Thanks, Peter! The lure of eval() once more avoided...
--
boB
More information about the Tutor
mailing list