What happens after return statement?

Tim Roberts timr at probo.com
Tue Oct 22 06:25:05 CEST 2002


Andreas Jung <lists at andreas-jung.com> wrote:
>
>--On Montag, 21. Oktober 2002 03:41 +0000 Gustaf Liljegren 
><gustafl at algonet.se> wrote:
>
>> I really ought to know better after 2 years with Python, but I became
>> uncertain. Have a look, please:
>>
>># Return the contents of a file (strip DOCTYPE conditionally)
>> def read_file(file, remove):
>>   if sys.path.exists(file):
>>     f = open(file, 'r')
>>     if remove = 0: # Just read the file
>>       return f.read()
>>     else: # Read the file and remove any line starting with '<!DOCTYPE'
>>       sum = ""
>>       while 1:
>>         line = f.readline()
>>         if line = "": break
>>         if line[:9] != '<!DOCTYPE':
>>           sum = sum + line
>>       return sum
>>     f.close() # Is the file closed (in both cases) here?
>^^^^^^^^^^^^^^^^^^^
>
>Why should that work?

Well, mostly because it DOES work.  In each case, the return statements
cause the last reference to the file "f" points at to go away.  When that
happens, the file itself will be closed automatically.
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list