20
votes

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?

4
The function will always return True or raise an error, so the return isn't too useful here. - Blender
thank you ! and these your answers inspired me very much, i think i will ask more on stackoverflow and also do what i can. - zds_cn
FYI, f.writelines(line+'\r\n') happens to work, but it's incredibly wasteful; it's treating the argument as a sequence and writing out each element; str are iterables of their characters, so it's effectively write-ing each character individually (buffering saves you from actual system call overhead, but it's still a lot more work). f.write(line+'\r\n') would get the same result, and write as a block, not character by character. - ShadowRanger

4 Answers

32
votes

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.

3
votes

The function always returns None if explicit return is not written.

2
votes

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

-1
votes

It does not make much sense to have a return statement on its own without being attributed or checked for a functionality.

Python returns None if nothing is returned. In your case you should probably return true if the opening file and writting is successful