Given this example function:
def writeFile(listLine,fileName):
'''put a list of str-line into a file named fileName'''
with open(fileName,'a',encoding = 'utf-8') as f:
for line in listLine:
f.writelines(line+'\r\n')
return True
Does this return True
statement do anything useful?
What's the difference between with it and without it? What would happen if there were no return function?
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.
A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed.
If a function doesn't specify a return value, it returns None
.
In an if/then conditional statement, None
evaluates to False. So in theory you could check the return value of this function for success/failure. I say "in theory" because for the code in this question, the function does not catch or handle exceptions and may require additional hardening.
The function always returns None
if explicit return
is not written.
If you have the return True
at the end of the function, you can say stuff like: a=writeFile(blah, blah)
However, because it will always be True
, it is completely pointless. It would be better to return True if the file was written correctly, etc.
If you don't explicitly return anything, the value will be None
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