In  Python, like most modern  programming languages, the function is a primary method of abstraction and encapsulation. You’ve probably written hundreds of functions in your time as a developer. But not all functions are created equal. And writing “bad” functions directly affects the readability and maintainability of your code. So what, then, is a “bad” function and, more importantly, what makes a “good” function?

A Quick Refresher

Math is lousy with functions, though we might not remember them, so let’s think back to everyone’s favorite topic: calculus. You may remember seeing formulas like the following f(x) = 2x + 3. This is a function, called f, that takes an argument x, and “returns” two times x + 3. While it may not look like the functions we’re used to in Python, this is directly analogous to the following code:

def f(x):
    return 2*x + 3

Functions have long existed in math, but have far more power in computer science. With this power, though, comes various pitfalls. Let’s now discuss what makes a “good” function and warning signs of functions that may need some refactoring.

Keys To A Good Function

What differentiates a “good” Python function from a crappy one? You’d be surprised at how many definitions of “good” one can use. For our purposes, I’ll consider a Python function “good” if it can tick off most of the items on this checklist (some are not always possible):

  • Is sensibly named
  • Has a single responsibility
  • Includes a docstring
  • Returns a value
  • Is not longer than 50 lines
  • Is idempotent and, if possible, pure

For many of you, this list may seem overly draconian. I promise you, though, if your functions follow these rules, your code will be so beautiful it will make unicorns weep. Below, I’ll devote a section to each of the items, then wrap things up with how they work in harmony to create “good” functions.

#python

Write Better Python Functions
1.80 GEEK