22

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
zds_cn
  • 278
  • 1
  • 2
  • 9
  • The function will always return `True` or raise an error, so the `return` isn't too useful here. – Blender Mar 12 '13 at 06:58
  • 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 Mar 12 '13 at 09:36
  • 1
    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 Jan 27 '16 at 17:18

4 Answers4

36

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.

Travis Bear
  • 13,039
  • 7
  • 42
  • 51
  • 2
    +1 for actually explaining that None is equal to False in terms of truth values. –  Mar 12 '13 at 07:52
  • i am sorry i am just a beginner,i will take care when the function needs handling exception.by the way ,i had tested that if i return nothing,it would return None.thanks – zds_cn Mar 12 '13 at 09:32
4

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

GodMan
  • 2,561
  • 2
  • 24
  • 40
2

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

Will Richardson
  • 7,780
  • 7
  • 42
  • 56
-1

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

dora
  • 1,314
  • 2
  • 22
  • 38