[Tutor] Use flag to exit?

Steven D'Aprano steve at pearwood.info
Thu Jun 24 13:54:23 CEST 2010

On Thu, 24 Jun 2010 08:51:26 pm Richard D. Moores wrote:

> How about using sys.exit() instead?

sys.exit() is almost always evil. Here's the problem:

One day, you find a nice library that has some function you need. 
Perhaps it's even a library you wrote yourself:

from library import print_next_prime

=> prints 7

And it works fine. So you decide to extend your program:

from library import print_next_prime

=> prints 7

And mysteriously it stops working. The second function call never 
happens, only the first. What's going on?

Eventually you work out that the print_next_prime function needlessly 
calls sys.exit. This being Python, you can fix it:

from library import print_next_prime

def print_next_prime2(n):
    except SystemExit:


so it's not the end of the world, but you shouldn't have to work around 
the poor design of the function in the first place.

sys.exit is almost never needed. I'm yet to find a program that includes 
it where the program wouldn't be simpler to use, more flexible, more 
friendly, and generally more useful, without it.

One (rare) exception is, when it is part of the user interface, not the 
backend. For instance, in a GUI application, you might link the Quit 
menu command to sys.exit.

In Python, you rarely need to explicitly exit because your code will 
exit when it reaches the end of the file, or on an un-caught exception.

Steven D'Aprano

More information about the Tutor mailing list