Search code examples
pythonstylesconventions

Should a function print a string or return it?


I'm writing a Python script, and it needs to print a line to console. Simple enough, but I can't remember (or decide) whether the accepted practice is to print in the function, for example:

def exclaim(a):
    print (a + '!')

or have it return a string, like:

def exclaim(a):
    return (a + '!')

and then print in the main script. I can make an argument for either method. Is there a generally accepted way to do this or is it up to preference?


EDIT: To clarify, this isn't the function I'm working with. I don't feel comfortable posting the code here, so I wrote those functions as an oversimplified example.


Solution

  • Normally a function should generate and return its output and let the caller decide what to do with it.

    If you print the result directly in the function then it's difficult to reuse the function to do something else, and it's difficult to test as you have to intercept stdout rather than just testing the return value.

    However in this trivial example it hardly seems necessary to either reuse or test the function, or even to have the function at all.