What happens after return statement?
Andreas Jung
lists at andreas-jung.com
Tue Oct 22 00:32:56 EDT 2002
I just call that bad programming style.
-aj
--On Montag, 21. Oktober 2002 21:25 -0700 Tim Roberts <timr at probo.com>
wrote:
> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
---------------------------------------------------------------------
- Andreas Jung http://www.andreas-jung.com -
- EMail: andreas at andreas-jung.com -
- "Life is too short to (re)write parsers" -
---------------------------------------------------------------------
More information about the Python-list
mailing list