Fake Python switch statement

Python has no switch statement.

what is switch statement ? switch statement is an alternate to if - elseif - else statement.

Example in C


  int payment_status=1;
    switch(payment_status){
    case 1:
        process_pending_payment();
        break;
    case 2:
       process_paid();
        break;
    case 3:
        process_trans_failure();
       break;
    default:
       process_default();
}

In python we can achieve same behaviour using dict.

Fake switch statement in python

payment_functions = {
    1: process_pending_payment,
    2: process_paid,
    3: process_trans_failure
}
try:
    status =2
    payment_functions[status]()
except KeyError:
    process_default()

In above code payment_functions is dict, where key is the one of the value of status and corresponding value is function to be invoked(but () is not present immediately).

When we try to access the dict element function name and () is present immediately so function is called. If key is absent KeyError exception is raised, default function is placed inside except block.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Powered by Buttondown.