1

Research

Lately, I've been playing around with different ways to write the same python code. One of the most exciting things I found was the discussion surrounding the use of a dict of functions to replace the use of if ... else (as shown in some of the answers to this question) and it seems that the overall understanding is that it is better performance-wise, but it might reduce the code's readability.

Code

Similarly, I tried using a dict of boolean keys and function values with a .get(...)() at the end. The only problem is that it is limited to only two functions.

Then, I came up with this solution (it sounds confusing but I don't know how else to put it):

  • using a list of functions indexed with the value returned from the .index(True) method of a list of conditions (booleans).

Here is the overall syntax:

  • [f_a, f_b, ..., f_n, default][[condition_a, condition_b, ..., condition_n, True].index(True)](*args)

And an example:

def foo(x):
    print("x is greater then 10")

def bar(x):
    print("x is negative")

def baz(x):
    print("x is 5")
   

x = int(input("x: ").strip())

[foo, bar, baz, lambda x: None][[x > 10, x < 0, x == 5, True].index(True)](x)

Question

All in all, I know that this is not pythonic at all, it has terrible readability and it would be a nightmare to debug and maintain, but I was wondering how would this impact the performance of my code. I also wanted to know if it was all lambda functions inside the list would it be better or worse?

David Camp
  • 322
  • 2
  • 9

0 Answers0