3

I hope my question does not sound too silly - but is it good programming practice to use return and print statement one after the other in the same function in Python?

e.g.

def test():
    ...
    if retval < 0:
            errval = "Error in reading value"
            print errval
            return errval

'errval' is being used by another function, and it also has to be printed. Any advice would be appreciated, thanks!

1
  • 4
    It might be better practice to print it outside of the function. Or, if this is actually and error, maybe you should raise an exception with a descriptive name instead? Commented Mar 27, 2015 at 11:46

1 Answer 1

1

My general advice:

  • Ideally, the bulk of your program consists of functions (or methods) that return data, mutate the state of self (for object-oriented code), or raise exceptions. In that world, printing is rarely, if ever, done.

  • Surrounding that data-oriented core, your program might have various needs to print. But even there, I suggest that you never print directly. Instead, write a printing function. That way, as your program grows more complex, you'll be able to manage printing behavior in a more consistent way.

  • Regarding your specific question ... it depends. How is this function being used, what is its place within the larger program, what is the expected behavior of that program, and so forth? But in general, I suspect that I would not write a function that prints an error message and then returns it. If I saw that in a colleague's code, it would catch my eye and I would think hard about whether there is a better design for the problem at hand.

  • As always, have the good sense to ignore general advice when the specifics of a situation demand it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.