Some Best Practices When Writing Python Functions [Intermediate Python Functions Series #7]

You’ve covered a lot of material in this Intermediate Python Functions Series. In this final article, you’ll read about some best practices in Python functions.

This topic is different from the previous ones discussed in this series. You won’t get a SyntaxError, TypeError or any other error if you don’t follow best practices. Your code may still work exactly the same if you use best practices or if you don’t, although bugs are more likely to creep into your code if you don’t.

Let’s see why it still matters to know and use best practices. There were two options when writing this article: either write a very long article covering every possible best practice or write a much more concise article highlighting two key best practices. I’ve chosen to go down the route of writing a short article and focus on the two I think are most relevant.

Overview Of The Intermediate Python Functions Series

Here’s an overview of the seven articles in this series:

  1. Introduction to the series: Do you know all your functions terminology well?
  2. Choosing whether to use positional or keyword arguments when calling a function
  3. Using optional arguments by including default values when defining a function
  4. Using any number of optional positional and keyword arguments: args and kwargs
  5. Using positional-only arguments and keyword-only arguments: the “rogue” forward slash / or asterisk * in function signatures
  6. Type hinting in functions
  7. [This article] Best practices when defining and using functions

Start The Function Name With A Verb

Let’s start with a function you’ve seen often in this series of articles:

def greet_person(person, number):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

It is clear from the name of the function what the function does. It greets a person! If you choose to call the function greeting(), it will be unclear what the function is doing with that greeting.

And you should always avoid calling a function func() or my_function() or other names with no descriptive value.

Let’s look at another example. Let’s assume you’re reading code that displays shapes and patterns. You see a function called square(). Is this function drawing a square or working out the square of a number to use in some calculation? You may be able to figure this out quickly by reading further or running the code. However, if the function name were draw_square(), you wouldn’t even need to ask yourself the question about the function’s purpose.

Did you notice what’s common in the two best practice examples you read about above? Here are a few more examples of best practice in Python function names compared to versions that you should avoid:

Use this……instead of this
calculate_score() or find_score()score()

A function performs an action. In the languages we use for human communication, such as English, verbs perform a similar role of denoting an action. Therefore, the best practice in Python functions is to use a verb as the first word in a function name to describe what the function does.

In the examples you read in the table above, the parameter name is also different in some cases. This series is about functions, so I’ll focus on function names. But when choosing variable names, including parameter names, you often want to use a noun which tells you what the value stored in the variable represents.

Write A Function That Only Does One Thing

Let’s assume you’re writing a program that deals with historical temperatures which you want to analyse. The data is in Fahrenheit, but you need to work in Celsius and then find the range of temperature in a subset of the data by subtracting the minimum value from the maximum value.

You decide to write the function convert_to_celsius_and_find_range(). You’ve followed the ‘start with a verb’ best practice and feel you’ve written a descriptive name. All good, then, right?

There’s a word in your function that’s a giveaway for the next best practice I’ll write about. This is the word “and” in the function name. If you feel the need to add an “and” in your function name, you probably want to write two functions instead.

A function should only perform one action. In this example, you can write a convert_to_celsius() function and another function called find_temperature_range().

This rule sounds simple enough initially. However, some nuance is involved in defining a “single action”.

For example, consider the function get_initials(full_name), which takes a string with a person’s full name and returns a string with the initials. This function may need to split the string to separate the components in the full name, such as first name, last name, and perhaps middle names. Then, it will need to extract the first letter from each subcomponent and concatenate them with periods after each letter.

These are several actions. Does this mean this function goes against the “perform one action” best practice? Every programmer will need to make these decisions in the context of the program and application they’re writing. In this example, it’s likely that grouping the steps listed above into a single get_initials() function is fine. The single action you want to perform is to get the initials from a name.

As a rule, if the steps you want to include in a function will always be performed together, then you probably want them in the same function. You’ll get better at making these decisions.

Final Words

Best practices in Python functions matter. They often make sure code is more readable for others and your future self. They also make bugs less likely and the code more maintainable.

Programmers will have different views on what constitutes a best practice. You’ll have to make up your mind on which ones to follow. And you may find that as you progress through your Python learning journey, you’ll also change your views on which best practices to adopt!

This is the final article in the Intermediate Python Functions Series

Further Reading

Subscribe to

The Python Coding Stack

Regular articles for the intermediate Python programmer or a beginner who wants to “read ahead”

8 thoughts on “Some Best Practices When Writing Python Functions [Intermediate Python Functions Series #7]”

  1. Re function names: I long ago learned to distinguish between two kinds of functions:
    1. Functions that *do* things.
    2. Functions that return a specific *value*

    In case 1, a verb is appropriate. The name should state what the function *does*.

    In case 2, a noun is appropriate. The name should state what the function *returns*.

    Case 2 occurs rather frequently, including in the standard library:
    “` python
    number_of_characters = len(“My full name”)
    `len` does *not* name an *action* that the function is taking. It names what the function *returns*.

    You’ll find this pattern *very* widely used in the industry, and it serves an important purpose: to make the code read more like natural language. “number of charactyers becomes the length of my full name.”

    Early programming languages distinguished the two cases syntactically. Th (Fortran and more advanced versions of BASIC were two of these.)

    Case 1 was a *subroutine*, defined via `SUB` and called via a `CALL` statement. Case 2 was a *function*, defined via DEF, and called in-line (as `len` is, above).

    1. Indeed, these considerations are always more complex and there are different style guides, too. In Python, the latter case you mention is often taken care of with properties, which are functions underneath the hood (methods) but are, as you say, named using the noun rather than the verb.
      I think there’s also a distinction to be made between key built-ins, such as `len()` as you suggest, which are accessing dunder methods behind the scenes, and other user-defined functions.

  2. I’m a fan of noun first names. It naturally groups related functions together: imagine working with files and your tab complete list is file_open, file_close, etc. vs open_file, open_socket, open_terminal, etc

    1. There will always be different style guides and different preferences on the topic of what’s “best practice”. This is why I ended the article with the caveat/warning: “Programmers will have different views on what constitutes a best practice. You’ll have to make up your mind on which ones to follow.”

Leave a Reply