What happens after return statement?

Chermside, Michael mchermside at ingdirect.com
Wed Oct 23 08:59:10 EDT 2002


> I really ought to know better after 2 years with Python, but I became 
> uncertain. Have a look, please:
	[... code ...]
> Is the file closed, or is it not? That is, what happens after each return 
> statement?
> 
> # Gustaf

Three points.

(1) Any time that a file gets garbage collected (and this happens
   as soon as it goes out of scope unless you have a reference
   loop) it will automatically be closed for you. So yes, the
   file is closed.

(2) Perhaps your question was really whether "return" causes the
   function/method to IMMEDIATELY exit, or whether it perhaps
   executes some additional code (outside of an if statement it
   might be in when you used "return"). The answer is that it
   IMMEDIATELY exits the function/method. No additional clean-up
   code is called.

(3) Perhaps your REAL question is HOW do I call some clean-up
   code. For example, some consider it poor form to allow a file
   to close itself instead of calling close() on it. Or you might
   have some other form of cleanup needed. The answer to THIS
   question is "try-finally", which works like this:

            >>> def f():
            ... 	try:
            ... 		print 'doing work'
            ... 		return 'some value'
            ... 	finally:
            ... 		print 'doing cleanup'
            ... 		
            >>> print f()
            doing work
            doing cleanup
            some value

-- Michael Chermside




More information about the Python-list mailing list