python – Is there a difference between quit and exit?

Question:

The type function shows that quit and exit are one object:

print(type(quit), type(exit))
# <class '_sitebuiltins.Quitter'> <class '_sitebuiltins.Quitter'>

The id function returns different identifiers:

print(hex(id(quit)), hex(id(exit)))
# 0x18caae42b70 0x18caae50630

The help function returns the same description:

Help on Quitter in module _sitebuiltins object:

class Quitter(builtins.object)
 |  Methods defined here:
 |  
 |  __call__(self, code=None)
 |      Call self as a function.
 |  
 |  __init__(self, name, eof)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

In the documentation the two functions have a general description

quit(code=None)
exit(code=None)

Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF)
to exit”, and when called, raise SystemExit with the specified exit code.


But there should be a difference, right?

Answer:

The short answer is that there is no difference, these are objects from the same Quitter class and the only difference will be in the name:

print(quit)
# Use quit() or Ctrl-Z plus Return to exit

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

I think quit and exit added for the convenience of working with the interpreter.


For more understanding, you need to look at the source code for _sitebuiltins.py :

class Quitter(object):
    def __init__(self, name, eof):
        self.name = name
        self.eof = eof
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, self.eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)

And also the source code for site.py :

def setquit():
    """Define new builtins 'quit' and 'exit'.
    These are objects which make the interpreter exit when called.
    The repr of each object contains a hint at how it works.
    """
    if os.sep == '\\':
        eof = 'Ctrl-Z plus Return'
    else:
        eof = 'Ctrl-D (i.e. EOF)'

    builtins.quit = _sitebuiltins.Quitter('quit', eof)
    builtins.exit = _sitebuiltins.Quitter('exit', eof)

Similar answer on SO

Scroll to Top