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.

đź§  Pro Tip

Skip the extension — just come straight here.

We’ve built a fast, permanent tool you can bookmark and use anytime.

Go To Paywall Unblock Tool
Sign up for a free account and get the following:
  • Save articles and sync them across your devices
  • Get a digest of the latest premium articles in your inbox twice a week, personalized to you (Coming soon).
  • Get access to our AI features

  • Save articles to reading lists
    and access them on any device
    If you found this app useful,
    Please consider supporting us.
    Thank you!

    Save articles to reading lists
    and access them on any device
    If you found this app useful,
    Please consider supporting us.
    Thank you!