views:

129

answers:

3

For the example below:

 if a == 100:
     # Five lines of code
 elif a == 200:
     # Five lines of code

Five lines of code is common and repeating how can I avoid it? I know about putting it a function

or

if a == 100 or a == 200:
    # Five lines of code
    if a == 100:
        # Do something
    elif a == 200:
        # Do something

Any other cleaner solution?

+4  A: 

Alternative (1): put your 5 lines in a function, and just call it

Alternative (2)

if a in (100, 200):
   # five lines of code
   if a == 100:
      # ...
   else:
      # ...

A little less verbose than your code

Eli Bendersky
+1 for alternative 1. Alternative 2 is hideous :-)
paxdiablo
@paxdiablo: the `else` is just omitting the superfluous, so the usage of `in` remains. why is it hideous in your opinion?
Eli Bendersky
I'm not a big fan of the dual-ifs (that's just a subjective thing, it's not gospel). I'd prefer refactoring any decent-sized commonality into a function.
paxdiablo
+1  A: 
def five_lines(arg):
  ...

if a in [100,200]:
    five_lines(i)
ghostdog74
Did you mean `if` instead of `for`?
Roger Pate
yes. thanks for catching that.
ghostdog74
+1  A: 

Remember that with functions, you can have local functions with a closure. This means you can avoid passing repetitive arguments and still modify locals. (Just be careful with assignments in that local function. Also see the nonlocal keyword in Python 3.)

def some_func(a):
  L = []

  def append():
    L.append(a)  # for the sake of example
    #...

  if a == 100:
    append()
    #...
  elif a == 200:
    append()
    #...
Roger Pate