jeudi 6 juillet 2023

Using a dictionary dispatch with a tuple - facing issues with args

from collections import defaultdict
#I have over 15 such functions
def sub_scenario_J_Conf(data):
    if data["cnt"] == "J" and data["data_class"].lower() == "conf":
        if data["cnt"] == "J" or data["person"] > 50 or data["person_no"] >= 500:
            return "A"
        elif data["cnt"] != "J" or data["person"] < 50 or data["person_no"] <= 500:
            return "B"
        else:
            return "F"
    else:
        return "Invalid option"

def sub_scenario_W_Conf_misdirected(data):
    if data["cnt"] == "W" and data["data_class"].lower() == "conf" and data.get("inc") == "diff":
        if data["person"] > 50 or data["person_no"] >= 500:
            return "A"
        elif data["person"] < 50 or data["person_no"] <= 500:
            return "B"
        else:
            return "F"
    else:
        return "Invalid option"

cases = defaultdict(lambda: lambda data: "Invalid option", {
    ("J", "Conf"): sub_scenario_J_Conf,
    ("W", "Conf", "diff"): sub_scenario_W_Conf_misdirected,
})

#fails here
data = {
    "cnt": "J",
    "data_class": "Conf",
    "person": 60,
    "person_no": 1000
}
#works here
data2 = {
    "cnt": "J",
    "data_class": "Conf",
     "data_diff":"diff",
    "person": 60,
    "person_no": 1000
}

sub_scenario_func = cases.get((data["cnt"], data["data_class"], data.get("inc", "")))
if sub_scenario_func:
    result = sub_scenario_func(data)
else:
    result = "Invalid option"

print(result)

data.get("inc", "") I am facing an issue with this, as it is unable to handle conditions where some functions take an input of two, while some take 3 or 4. How do I fix this? Also, if there is a better way to deal with the if conditions, do let me know, it would be of great help .

Aucun commentaire:

Enregistrer un commentaire