Data Mastery
Data Mastery

Reputation: 2095

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?

Upvotes: 0

Views: 34

Answers (1)

Tom Ron
Tom Ron

Reputation: 6181

You can minimize the if else block to -

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

Upvotes: 1

Related Questions