1

For example, let's say I have a bunch of assignment statements like this:

if operator == '==':
   if a == b:
       c += 5
elif operator == '>':
   if a > b:
       c += 5
elif operator == '<':
   if a < b:
       c += 5

The if nested if statements and assignments I gave are just examples but in the program I'm writing, they are really long. Just a small change is present where the operators differ, so I don't want to have to repeat the same long piece of code over and over again just for all these conditions. There are too many conditions and the code will get repeated many times..so is there a "faster" way to do this? Can I maybe define a string as an operator? Or any better ways?

0

3 Answers 3

6

How about:

from operator import *

str_ops = {'<':lt,'>':gt,'==':eq} # etc
op = str_ops.get(my_operator) #where my_operator was previously your 'operator'
assert op is not None #or raise your own exception
if op(a,b):
    c+=5

And, if you wanted to gracefully handle a bogus operator in my_operator, you can do:

op = str_ops.get(my_operator, lambda x,y: None) #fallback: do-nothing operator

Bonuses to this approach:

  • ONE if statement. No matter how many operators you're handling.
  • O(1) behavior, as opposed to O(n) with branching if/elif statements.
  • The dict is very declarative: this string goes to this operator.
  • Doesn't Repeat Yourself.
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Nice one :), you might wanna handle non existent case as well.
By operators you mean str_ops right? In that case, you dont need lambda to return None. You can simply say None
@thefourtheye well, None is the default fall-back from .get, so I wouldn't need to specify that. And I do need a lambda there, since None(a,b) doesn't work out so well.
3

You can use and and or operators effectively, like this

if (operator == '==' and a == b) or (operator == '>' and a > b) \
      or (operator == '<' and a < b):
    c += 5

Comments

2

As an alternative solution, if you can trust the source of the operator string (or have some way of validating it) you can use eval. But you have to be really careful when using eval; it can be a big security risk if you don't trust the source of the input.

if eval("a %s b" % operator):
    c += 5

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.