A tour in making conditionals more Pythonic
Dear reader, you might think this letter is just a programming blog now. I think it might just be. It was not my intention but my work and hobby revolve around code, coffee, and food. And I only have enough expertise to write only in the first item. So here we are.
That said, today’s post is about how you can avoid long conditionals in Python by substituting them with dictionaries. Let’s consider a hypothetical streaming service where a function routes requests based on a series of conditionals.
The if-else statements are not too bad here but you can imagine how future feature requests can make this lengthier and clunkier. In any case, it doesn’t look good right now and in my opinion, it does not meet the Python style guide of “Simple is better than complex.” Let me show you an alternative for this conditional that is more readable, maintainable, and extendable.
Instead of using multiple if-else statements, we simply declare a dictionary with the statement condition arguments as keys and a series of lambda functions instead of the execution statements. Using this is as simple as getting the correct lambda function from the dictionary and calling it. The fallback condition of the else condition is now replaced by another lambda in the dictionary get statement. While it might be a doozy the first couple of times, especially if you don’t use lambdas often, it is easy to get the hang of it. Maintenance and extension are easy since each condition is a separate item in the dictionary and thus modularized and easy on the eyes.
I hope this tip helps you be more Pythonic and helps you have more fun :)