[Tutor] break and exit

Peter Otten __peter__ at web.de
Fri Nov 21 09:20:00 CET 2014


James Rieve wrote:

> I accidently used 'exit' in a loop where I meant to use 'break' and, in
> that case, the program seemed to work as expected but in some cases 'exit'
> seems to behave differently from 'break'. For example, in this code
> snippet using 'exit' or 'break' produces the same result:
> 
> for i in range(10):
>     if i > 3:
>         exit
>     else:
>         print(i)
> print('out of loop')
> 
> But in this case they behave differently:
> 
> for i in range(10):
>     if i > 3:
>         break   # try using exit here.
>     else:
>         print(i)
> else:
>     print('for loop else statement')
> 
> print('out of loop')
> 
> Does anyone have any pointers to descriptions of 'exit', what it is, what
> it means, how It's used, etc.?

exit is not part of Python's syntax, it is (almost, see below) a normal 
function. Writing

exit

has no effect, instead of

> for i in range(10):
>     if i > 3:
>         exit
>     else:
>         print(i)
> print('out of loop')

you could have written

for i in range(10):
    if i > 3:
        pass
    else:
        print(i)
print('out of loop')

but if you invoke exit like a function

> for i in range(10):
>     if i > 3:
          exit()
>     else:
>         print(i)
> print('out of loop')

the script will be terminated -- you can detect that by the fact that

out of loop

is not printed. Personally, I hardly ever use exit (or sys.exit() or `raise 
SystemExit`). If you want a script to stop in the middle of execution I 
recommend that instead of

print("some code")
if some_condition:
   exit()
print("more code")

you write

print("some code")
if not some_condition:
    print("more code")

or (even better for all but tiny scripts) use a main function like so:

def main():
    print("some code")
    if some_condition:
        return
    print("more code")

if __name__ == "__main__":
    main()

Now -- what actually is exit? Let's fire up the interactive interpreter:

$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> help(exit)
Help on Quitter in module _sitebuiltins object:

class Quitter(builtins.object)
 |  Methods defined here:
 |  
 |  __call__(self, code=None)
 |  
 |  __init__(self, name, eof)
 |  
 |  __repr__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

So exit is an instance of Quitter. The Quitter class has a __call__ method 
which is executed when you invoke an instance like a function. Let's have a 
look a the code:

>>> import inspect
>>> print(inspect.getsource(exit.__call__))
    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)

So exit() tries to close sys.stdin and then raises a SystemExit exception. 
Unless you catch that exception the program ends.





More information about the Tutor mailing list