Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't I use exit() in Python programs?

Tags:

python

exit

According to Difference between exit() and sys.exit() in Python, the preferred way to exit from a Python application is to use sys.exit(). Python's documentation states that exit() should only be used to exit from the interactive shell.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.

While the documentation warns against using constants from the site module, it doesn't explain why we shouldn't use them.

Why shouldn't exit() be used in Python applications?

like image 332
Stevoisiak Avatar asked Sep 08 '25 02:09

Stevoisiak


1 Answers

The site module, which is responsible for injecting exit() and other things into global scope for convenience in the REPL, is not guaranteed to be loaded. If you rely on it, and it's not there, your app will break unexpectedly.

Just to be safe, from sys import exit will do you no harm.

like image 143
Adam Barnes Avatar answered Sep 10 '25 08:09

Adam Barnes