-2

I have a small fastapi application that can get 4 optional arguments from the user, and based on the user's input run a matching function like so:

def do_function(origin, destination, departure, arrival):
    if departure is None and arrival is None:
        do_a(origin, destination)
    elif departure is not None and arrival is None:
        do_b(origin, destination, departure)
    elif departure is None and arrival is not None:
        do_c(origin, destination, arrival)
    elif departure is not None and arrival is not None:
        do_d(origin, departure, arrival)
    elif departure is not None and arrival is None:
        do_e(origin, departure)  

    # and so on...

What is the most pythonic way of executing this code without using long and tiering "if-elif"?

I've seen a similar question here: most efficient way to selection specific function based on input , but it doesn't apply to my case where there are only 4 optional inputs and more than 4 function options.

  • You already have a duplicate in the cases shown. There are only 4 combinations. Aside from that, the question can't be answered in general; it depends on **why** there are separate functions `do_a`, `do_b` etc., and **why it matters** whether the values are `None`. – Karl Knechtel Feb 14 '23 at 16:39

2 Answers2

1

Use Structural Pattern Matching (3.10+)

This situation is a very good one to use Structural Pattern Matching.

def do_function(origin, destination, departure, arrival):
    match (origin, destination, departure, arrival):
        case (origin, destination, None, None):
            print(origin, destination)
        case (origin, destination, departure, None):
            print(origin, destination, departure)
        case (origin, destination, None, arrival):
            print(origin, destination, arrival)
        case (origin, destination, departure, arrival):
            print(origin, departure, arrival)

Here is a tutorial on structural pattern matching, and here is the PEP 622.

Dorian Turba
  • 3,260
  • 3
  • 23
  • 67
  • it doesn't work for: origin = 'TLV', destination = None, departure = 'NYC', arrival = None, it goes to the second case although it shouldn't – Daniel Avigdor Feb 15 '23 at 15:14
-1

Create a map dict[tuple[bool, bool], function]:

function_map = {
   (True, True)  : foo,
   (True, False)  : bar,
   ...
}
func_key = departure is None, arrival is None
function_map[func_key](origin, departure, arrival)
Axeltherabbit
  • 680
  • 3
  • 20