Returning None Explicitly
00:00
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.
00:19
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 None
.
00:35
Let’s verify that all three of these cases actually do return a value of None
. So, here’s a function with no return
statement.
00:47
Remember, we use the keyword pass
to indicate an empty function body. If we just call this function,
00:57
we don’t see anything. Remember, the interpreter won’t show a return value of None
. You actually have to print the result of a function call to see that it does indeed return None
.
01:11
Next, we’ll look at having just a bare return
statement,
01:17
so we’ll have return
but no return value. If we print the result of its function call, we get None
. And lastly, we can explicitly return None
.
01:36
We return None
, and print the result of its function call.
01:46
We see we get None
again. So all of these return None
. So, what are some factors to consider when you need to decide which to use?
01:56
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.
02:09
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.