Just Stop Writing Python Functions Like This!!! | by Kiran Maan | Python in Plain English


This article critiques a Python function with multiple flags, highlighting the confusion this causes and suggesting better design choices for improved code readability.
AI Summary available — skim the key points instantly. Show AI Generated Summary
Show AI Generated Summary

Just Stop Writing Python Functions Like This!!!

Last week, I was reviewing someone else’s code. I just stumbled upon a Python function that made me feel whether I must cry or laugh.

Image generated by AI

Then I decided to write about that incident…so that you didn’t make the same mistake.

Not a medium member, yet? Read it FREE here.

Terrible Code About Which I am Talking About

This was the code that just made me feel like this:

def process_data(data, flag1, flag2, flag3):    if flag1:        data = [item for item in data if item.isdigit()]    if flag2:        data = [item.upper() for item in data]    if flag3:        data = sorted(data)    result = "Processed: " + ", ".join(data)    return result

This code doesn’t seem that much bad at first glance. But let me tell you why I am saying this to be terrible:

At first glance, it doesn’t seem too bad, right? But let’s understand what’s wrong with this code.

1. Too Many Flags

It’s using too many flags (flag1, flag2, flag3) to control behavior, which is making the function a little bit confusing.

In this, every time we are calling a function, we have to figure out which combination of flags is producing the desired result.

Let me explain this with the help of this example

res = process_data(my_data, True, False, True)

Did you understand what does True, False, True even means? This is the same case with the above function.

Was this article displayed correctly? Not happy with what you see?

Tabs Reminder: Tabs piling up in your browser? Set a reminder for them, close them and get notified at the right time.

Try our Chrome extension today!


Share this article with your
friends and colleagues.
Earn points from views and
referrals who sign up.
Learn more

Facebook

Save articles to reading lists
and access them on any device


Share this article with your
friends and colleagues.
Earn points from views and
referrals who sign up.
Learn more

Facebook

Save articles to reading lists
and access them on any device