Leveraging Python's Implicit 'return None' Statements

preview_player
Показать описание

Python adds an implicit "return None" statement to the end of any function. Therefore, if a function doesn't specify a return value it returns None by default.

This means you can replace return None statements with bare return statements or even leave them out completely and still get the same behavior in your programs.

In this video tutorial I show you the rundown of how implicit return statements work in Python and how you can use them to make your code cleaner and more Pythonic.

I also cover the potential downsides of using this feature and how it can make your code *harder* to read in some cases.

On the one hand, you could argue that omitting an explicit return None statement makes the code more concise and therefore easier to read and understand. Subjectively you might also say it makes the code "prettier."

On the other hand, it might surprise some programmers that Python behaves this way. When it comes to writing clean and maintainable code, surprising behavior is rarely a good sign.

Watch the video for the full discussion.

* * *

FREE Python Tutorials & News:
Рекомендации по теме
Комментарии
Автор

Hello,

And PEP8 recommends:
 "
Be consistent in return statements. Either all return statements in
a function should return an expression, or none of them should. If
any return statement returns an expression, any return statements
where no value is returned should explicitly state this as

return
None

, and an explicit return statement should be present at the
end of the function (if reachable).


Yes:

def foo(x):
if x >= 0:
return math.sqrt(x)
else:
return None

def bar(x):
if x < 0:
return None
return math.sqrt(x)


No:

def foo(x):
if x >= 0:
return math.sqrt(x)

def bar(x):
if x < 0:
return
return math.sqrt(x)

"

JCRMatos
Автор

I just found out about this series and I've been hooked on it. Great content!

lakshaykalbhor
Автор

How do you if value match return the matching value

Dopeboyz
Автор

Can you please open up on Python compiler and interpreter

subrahmanyeswaraswamymurala
Автор

ı really appreciate your effort. maybe my background is not enough for it. but very confusing :(

enverozdemir
Автор

I disagree.

Import this #2 Mr Dan.

"Explicit is better then Implicit"

simest