2

I have an if-elif-else structure with multiple levels, but the last-level else is always the same statement:

if statement1:
    if something:
        do_thing()
    elif something_else:
        if something_something:
            do_thing_something()
        elif somethingg:
            do_thingg()
        else:
            do_default()
    else:
        do_default()
else: 
    do_default()

As you can see, I use do_default() 3 times, and I feel like there's a better way. This would basically be a default in a switch-case statement in other languages, but Python does not have switch-case. I was wondering if there's any other way I could solve this more elegantly/"Pythonically"? Or is the only way to use dicts or implement my own switch-case?

Jab
  • 26,853
  • 21
  • 75
  • 114
lte__
  • 7,175
  • 25
  • 74
  • 131

3 Answers3

5

You could try un-nesting your conditionals:

if statement1 and something:
    do_thing()
elif statement1 and something_else and something_something:
    do_thing()
elif statement1 and something_else and somethingg:
    do_thingg()
else:
    do_default()
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

You could pack it into a function and write it as in

def wrapper(args):
    if statement1:
        if something:
            return do_thing()
        elif something_else:
            if something_something:
                return do_thing_something()
           elif somethingg:
                return do_thingg()
    do_default()

Though you do have to write return multiple times

kuco 23
  • 786
  • 5
  • 18
0

Pulling this block into a function may help:

def do_things():
    if statement1:
        if something:
            return do_thing()
        elif something_else:
            if something_something:
                return do_thing_something()
            elif somethingg:
                return do_thingg()
    return do_default()
0x5453
  • 12,753
  • 1
  • 32
  • 61