0

Apologies if this is the wrong way to ask this question.

So I did some basic google searches and looked at the PEP-8 recommendations, but I still can't find a good code guide for my question:

Is it better to exit my python script from within a function or to return 1 and let the __main__ body handle exiting?

Example:

def exit_fun():
  if foo:
    keep going
  else:
    exit(1)

if __name__ == "__main__":
  exit_fun()
  next_fun()

-or-

def exit_fun():
  if foo:
    keep going
  else:
    return 1

if __name__ == "__main__":
  funfun = exit_fun()
  if funfun == 1:
    exit(1)
  next_fun()

The frist way looks cleaner to my eyes but my eyes don't compare to a style guide.

Philipp
  • 876
  • 10
  • 23
ZeroWing
  • 1
  • 1
  • 1
    Why is the script exiting? Is that error handling? I'd find that jarring for a script to suddenly exit in the middle of execution. Rather I'd find it more canonical to `raise` a specific exception or use error codes. – Cory Kramer Jul 24 '17 at 14:12
  • 1
    Note that `exit(1)` is basically just `raise SystemExit(1)`. – Dietrich Epp Jul 24 '17 at 14:12
  • @CoryKramer: It's not unusual for a script to exit if it encounters an error. If you don't need any more error handling in your program than that, there's no need for exceptions or error codes (although `exit()` technically raises an exception). – Dietrich Epp Jul 24 '17 at 14:13
  • 1
    It _is_ better style for everything to return to `main` and let it handle exiting. BTW, the plain `exit` function is a bit odd. It's ok to use it in the interactive interpreter, but it's safer to use `sys.exit` in a proper script, or just `raise SystemExit`, as suggested by Dietrich Epp. Please see [Difference between exit() and sys.exit() in Python](https://stackoverflow.com/a/6501134/4014959). – PM 2Ring Jul 24 '17 at 14:15
  • @CoryKramer sorry to omit that, it isn't error handling as such (I'd used try/except stanzas for that) but more of a 'Does a prerequisite exist?' aka does an external script I'm calling exist on my system. – ZeroWing Jul 24 '17 at 14:15
  • @PM2Ring Thanks! I'm a python newb and I'm trying to make my code as stylishly correct as possible. – ZeroWing Jul 24 '17 at 14:19

1 Answers1

0

As PM2Ring wrote:

It is better style for everything to return to main and let it handle exiting.

So that answers that, also thanks everyone for the pointers of sys.exit() vs exit()

ZeroWing
  • 1
  • 1