lundi 20 novembre 2017

Most pythonic way of approaching a multiple conditionals function

Maybe it is just me, but I seem to come across this problem on almost a daily basis. I've heard in many places that function should be compact and easy to read.

I often have a scenario where I have multiple conditionals which all return different values. Something like.

def conditionals():
    if something1:
        return item1
    if something2:
        return item2
    if something3:
        return item3
         ...

With a lot more conditionals, the function is not compact and certainly not readable. The only way I found to make this better is to make a function specific to each item to return. But then in my code, I feel like I have so many functions for nothing. Anyway, what is the best way to solve this?

Aucun commentaire:

Enregistrer un commentaire