user3033194
user3033194

Reputation: 1831

Use return and print in the same function in Python

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!

Upvotes: 3

Views: 1010

Answers (1)

FMc
FMc

Reputation: 42421

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.

Upvotes: 1

Related Questions