All articles

Writing Python Functions: Common Mistakes and How to Fix Them

Writing Python Functions: Common Mistakes and How to Fix Them

Functions exist for reuse: code needed in several places is moved into a function and called with one line. That's why a poorly designed function costs a lot — the problem spreads to every call site, and the project gets harder and harder to maintain, both for you and your colleagues. I'll admit I've made some of these mistakes myself.

Below are common mistakes when writing functions in Python — from a signature that tells you nothing to mutable default values — and how to fix them.

1. A signature that says nothing

Imagine you've added someone else's library and see:

def f(value):
    ...

What does f do? What is value — a number, a string, a dict? What does the function return? You can only answer by opening the function body. It shouldn't be that way: the signature itself should explain what the function does, what it accepts and what it returns.

def get_last_orders(limit: int) -> list[Order]:
    ...

Now everything is clear without reading the code: the name says what the function does, the annotations say which types it accepts and returns. Your editor shows a hint on hover, and PyCharm, mypy or Pyright will flag an error if you pass a string instead of a number.

2. Clashing function names

If you declare two functions with the same name in one file, the second simply replaces the first — Python doesn't consider that an error. Within a single file it's noticeable. It's more dangerous when names clash across modules:

from helpers import *   # helpers has get_name


def get_name():          # your function silently shadows the imported one
    ...

Or the other way around: you declared a function, and an import below overwrote it. The program behaves oddly, and the cause is hard to find, because from Python's point of view everything is legal — maybe you really did mean to override the behavior. Give functions unique names across the whole project, import explicitly rather than with *, and split the program into modules with clear boundaries.

3. Comments about the wrong things

There are two extremes. The first is comments where everything is already clear:

# declare the function
def get_user_name(user: User) -> str:
    # return a string
    return user.name

The name and annotation have already said everything; the comments only get in the way. The second extreme is a non-obvious function without a single explanation. The rule is simple: a comment or docstring is needed where behavior isn't obvious — what the edge cases are, why this particular algorithm was chosen, what a confusing parameter means.

4. Vague names

processing, value_handler, message_handler — such names don't tell you what's going on. message_handler handles messages, but how: receives, sends, decrypts? Coming up with precise names is tedious — I'm guilty of this myself — but it pays off every time you come back to the code.

Bad Better
processing(data) normalize_phone_numbers(rows)
value_handler(v) parse_price(raw_price)
message_handler(msg) send_telegram_alert(text)

A good name is a verb plus an object: what we do and to what.

5. A set of functions around the same data instead of a class

If several functions work with the same value and pass it to each other, that's a reason to combine them into a class:

class Wallet:
    def __init__(self, balance: Decimal) -> None:
        self.balance = balance

    def deposit(self, amount: Decimal) -> None:
        self.balance += amount

    def withdraw(self, amount: Decimal) -> None:
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount

The state is initialized once in __init__, the methods work with it through self, and if needed you can add properties and validation. That's more convenient than passing one value through five independent functions. Functions aren't forbidden — a class is needed when the data has both state and behavior.

6. A function that does everything

def handler():
    data = load_json(...)      # reads JSON
    response = send_request()  # sends a request
    notify_telegram(response)  # posts to Telegram
    write_log(response)        # writes a log

While there's just one function, this seems convenient. Then test shows up, which also needs to write a log, and test2, which needs requests and a log. Code gets copied in chunks, and a bug has to be fixed in three places.

A function should do one thing. Reading JSON, sending a request, notifying and logging are four separate functions, and handler just calls them in order. Then any piece is easy to reuse and test on its own.

7. A mutable default value

The trickiest mistake:

def add_item(item, items=[]):
    items.append(item)
    return items


print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] — but we expected [2]

A default value is evaluated once — when the function is defined, not on every call. The list is created right away and stored in add_item.__defaults__, so every call without the argument works with the same object. You can check this with id(): the address doesn't change between calls.

The right way is to use None and create a new object inside:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

The same applies to dicts, sets and any mutable objects.

8. *args and **kwargs for no reason

def add(*args, **kwargs):
    if args:
        return args[0] + args[1]
    return kwargs["x"] + kwargs["y"]

It looks "advanced", but in reality the function has become unreadable: the signature doesn't say what to pass, and errors only surface at runtime. Simpler and more honest:

def add(x: float, y: float) -> float:
    return x + y

*args and **kwargs are needed where the number of arguments truly isn't known in advance — for example, in decorators and wrappers that pass arguments along. In years of programming in Python I've needed this only a handful of times.

A good function checklist

  • The name describes an action: a verb plus an object.
  • Type annotations for parameters and the result.
  • One task — one function.
  • Comments only for non-obvious behavior.
  • No mutable default values.
  • *args and **kwargs only when there's no way around them.
  • Related functions around shared data are a reason for a class.

Many of these rules are part of design principles like SOLID, which are covered in detail in my Python OOP course. And how mutable objects and lists behave in memory is explained in why a Python list can eat all your memory.

Sources