Huge if, elif, else Block

Since python has no native switch/case construct, I have a huge if/elif/else block. Is that really the right/efficient way to handle this situation?

You could use a dictionary mapping your possible values to callables instead, if your value is hashable

value = 42

def big_block():
    r = requests.get(url)
    return value * r.json()

cases = {
    42: lambda: 3,
    5: lambda: value * 5,
    21: big_block,
}

case = cases.get(value, lambda: None)
result = case()

A dict is the goto native option. Here’s a library when cases get more complex:

https://github.com/mikeckennedy/python-switch

1 Like

Thanks for the replies. I’ll give it a go.

I’m afraid I have been unsuccessful understanding how to do this. Most of the examples just return a value but in my case I need to run a function. I found some examples on how to do this but mine does not work. Here is an excerpt of my code:

def processCommand(self,cmd,sn,value,checkOnly):
    commands={
            'n1':setNone,
            'n2':setNone,
            'na':setNone,
            'al':setNone,
            'ta':setNone,
            'th':setNone,
            'tl':senNone,
            'sw':setNone,
            'fa':setNone,
            'qq':setSerial
        }
    commands.get(cmd)(sn,value)

def setNone(self,sn,val):
    print(sn,val)

def setSerial(self,sn,val)
    self.__showSerial=True

When I try to run this I get the error:

name ‘setNone’ is not undefined

Try self.setNone inside the commands dict instead. This snippet looks to be inside a class, so the setNone function is not part of the global scope, and instead needs to be called as a method of the class.

That was it, thanks. I bit subtle but none of the examples I found did that. Now that I see it, it makes sense.