Ank Ank - 1 year ago 213
Python Question

Exiting from python Command Line

To exit from Python command line, I have to type exit(). If I type exit, it says

Use exit() or Ctrl-Z plus Return to exit

Usually when you type
, you would want to exit the program. Why does the interpreter give me the above error when it knows I am trying to exit the command line? Why doesn't it just exit? I know it doesn't matter and its a silly question but I am curious.

Answer Source

When you type exit in the command line, it finds the variable with that name and calls __repr__ (or __str__) on it. Usually, you'd get a result like:

<function exit at 0x00B97FB0>

But they decided to redefine that function for the exit object to display a helpful message instead. Whether or not that's a stupid behavior or not, is a subjective question, but one possible reason why it doesn't "just exit" is:

Suppose you're looking at some code in a debugger, for instance, and one of the objects references the exit function. When the debugger tries to call __repr__ on that object to display that function to you, the program suddenly stops! That would be really unexpected, and the measures to counter that might complicate things further (for instance, even if you limit that behavior to the command line, what if you try to print some object that have exit as an attribute?)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download