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:
- Introduction to the series: Do you know all your functions terminology well?
- Choosing whether to use positional or keyword arguments when calling a function
- Using optional arguments by including default values when defining a function
- Using any number of optional positional and keyword arguments:
args
andkwargs
- Using positional-only arguments and keyword-only arguments: the “rogue” forward slash / or asterisk * in function signatures
- Type hinting in functions
- [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() orfind_score() | score() |
get_initials(full_name) | initials(fn) |
find_duplicates(book_name) | duplicates(a) |
remove_duplicates(book_name) | duplicates(a) |
add_team_member(name) | team_member(name) |
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
- Chapter 3: Power-up Your Coding: Create Your Own Functions for an in-depth introduction to Python functions
- Chapter 6: Functions Revisited. This chapter covers topics that will be dealt with later on in the series
- The White Room: Understanding Programming. In this article, I briefly referred to parameters as boxes which store data. This is part of a broader analogy I like to use. You can read more in this chapter
- Using Python Optional Arguments When Defining Functions is an article I wrote for Real Python if you want to read ahead.
Get the latest blog updates
No spam promise. You’ll get an email when a new blog post is published
The post Some Best Practices When Writing Python Functions [Intermediate Python Functions Series #7] appeared first on The Python Coding Book.