Returning None Explicitly
Now that you know the syntax of writing
return statements in Python, let’s take a look at some best practices when using it. First, we’ll look at returning
None explicitly. As you’ve seen, Python will return a value of
None in several situations, but there might be occasions to actually write out a
return None statement.
There are basically three ways to cause a value of
None to be returned from a function: if the function doesn’t have a
return statement at all, if you have a
return statement with no return value, or you can explicitly return
If your function performs actions but doesn’t have a clear and useful return value, then you can omit the
return statement, although you could use a bare
return statement just to make clear your intention of returning from the function.
If your function has multiple branches with
return statements and returning
None would be a reasonable value for one or more of those branches, then you should consider the explicit use of
return None instead of relying on Python’s default behavior. A word of caution: many Python programmers come from other programming languages, so not having a
return statement at all for a function might be confusing for those who are used to referring to such subprograms as procedures.
02:38 This might be an issue to consider in thinking about the long-term maintainability of your project. Next, we’ll look at two other best practices involving remembering the return value and avoiding complex expressions.
Become a Member to join the conversation.