lundi 29 juin 2020

Python function: Avoid using if clauses for parameter check

this is my function:

def save_to_mongo(self, df, collection, additional_variable):
    for index, row in df.iterrows():
        result = row.to_dict()
        collection.update_one(
            {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid']) + str(row[additional_variable])},
            {
                '$set': result
            },
            upsert=True)

I have many similar functions where parameters like the additonal_variable can be None.

I would really like to avoid to bloat up the codebase with a style like this:

if additional_varibale is None:
    collection.update_one(
        {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid'])},
        {
            '$set': result
        },
        upsert=True)
else:
    collection.update_one(
        {"_id": str(row['date']) + "_" + str(row['sector']) + "_" + str(row['caseid']) + str(row[additional_variable])},
        {
            '$set': result
        },
        upsert=True)

I think this code is ugly and hard to maintain. Are there any better ways or best practices to avoid using these long if and else statements?

Aucun commentaire:

Enregistrer un commentaire