Skip to content
Advertisement

Python Switch/Case Statement Adaptation

Ok, at the risk of being ridiculed for not ‘trying harder’, I have a scenario that I’ve been attempting to adapt to a pythonic switch case statement. I know python has the new match method in 3.10 but I’m limited to 3.8.10 in my AWS use case. I’ve been reading up on switch cases in other languages and I want to find a pythonic way to convert the following jumbled mess of if/elif/else statements to a clean switch case. I am wondering what others would do in this scenario

OBJECTIVE: I have a filename that will be passed into this sequence of code and I need to return the first three items (i.e. transaction_recipient_verification, transaction_account_tokenization, etc). Occasionally the code will receive a filename containing “field_results” or “issuers” and I need to make sure that the trimmed return string contains the respective case.

JavaScript

Possible Direction:

JavaScript

And the code to test the class:

JavaScript

Advertisement

Answer

I see a lot of repetition in your code, so the first thing I’ll think of would be: “can I use a loop to simply this code?” and the answer is yes!

Since your code repeatedly used the six subjectTypes and the keySubject depends on the subject type, creating a list of the six types then use next() with a generator expression should simplify the over abundance of if‘s (If there weren’t any correlations, a dictionary would work instead). Also, instead of array_data, you can use an if-elif-else clause to prevent an extra block level.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement