tailor_raj
tailor_raj

Reputation: 1057

difference between quit and exit in python

Would anybody tell me what is the difference between builtin function exit() and quit().

Please correct me if I am wrong at any point. I have tried to check it but I am not getting anything.

1) When I use help() and type() function for each one, it says that both are object of class Quitter, which is defined in the module site.

2) When I use id() to check the addresses of each one, it returns different addresses i.e. these are two different objects of same class site.Quitter.

>>> id(exit)
13448048
>>> id(quit)
13447984

3) And since the addresses remains constant over the subsequent calls, i.e. it is not using return wrapper each time.

>>> id(exit)
13448048
>>> id(quit)
13447984

Would anybody provide me details about the differences between these two and if both are doing the same thing, why we need two different functions.

Upvotes: 31

Views: 15109

Answers (1)

Mikhail Karavashkin
Mikhail Karavashkin

Reputation: 1365

The short answer is: both exit() and quit() are instances of the same Quitter class, the difference is in naming only, that must be added to increase user-friendliness of the interpreter.

For more details let's check out the source: http://hg.python.org/cpython

In Lib/site.py (python-2.7) we see the following:

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 = 'Cmd-Q'
    elif os.sep == '\\':
        eof = 'Ctrl-Z plus Return'
    else:
        eof = 'Ctrl-D (i.e. EOF)'

    class Quitter(object):
        def __init__(self, name):
            self.name = name
        def __repr__(self):
            return 'Use %s() or %s to exit' % (self.name, 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)
    __builtin__.quit = Quitter('quit')
    __builtin__.exit = Quitter('exit')

The same logic we see in python-3.x.

Upvotes: 28

Related Questions