A I couldn't find anything concerning in the PEP 8. I'm interested in your thoughts about the most pythonic syntax of function which have no return?
Are there any reason to prevent functions without a return line(example 3)?
Example 1:
def foo():
print 'foo'
return None
Example 2:
def foo():
print 'foo'
pass
Example 3:
def foo():
print 'foo'
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.
Python returns null function | Example code Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing'). You can do this explicitly and return None yourself though.
So, if you don't explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you. That default return value will always be None .
In Python, it is possible to compose a function without a return statement. Functions like this are called void, and they return None, Python's special object for "nothing". Here's an example of a void function: >>> def sayhello(who): print 'Hello,', who + '!'
Keep it simple. Example 3 is the most pythonic way.
>>> import this
The Zen of Python, by Tim Peters
...
Simple is better than complex.
...
The PEP8 has a recommendation on this topic:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With