Q on explicitly calling file.close

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Sep 11 04:21:35 EDT 2009


En Thu, 10 Sep 2009 08:26:16 -0300, David C. Ullrich  
<dullrich at sprynet.com> escribió:
> On Wed, 9 Sep 2009 15:13:49 -0700 (PDT), r <rt8396 at gmail.com> wrote:
>> On Sep 9, 4:19 pm, Charles Yeomans <char... at declareSub.com> wrote:

>>> I removed the except block because I prefer exceptions to error codes.
>>
>> how will the caller know an exception has occurred? What if logic
>> depends on the validation that a file *had* or *had not* been written
>> too, huh?
>>
>> Oh I see! But what happens if the filename does not exist? What then?
>> "open" will blow chucks thats what! Here is a version for our paranoid-
>> schizophrenic-sadomasochist out there...
>
> Well first, we agree that putting the open() in the try part of a
> try-finally is wrong. try-finally is supposed to ensure that
> _allocated_ resources are cleaned up.
>
> What you do below may work. But it's essentially throwing
> out exception handling and using error codes instead. There
> are plenty of reasons why exceptions are preferred. The
> standard thing is this:
>
> def UseResource(rname):
>   r = get(rname)
>   try:
>     r.use()
>   finally
>     r.cleanup()

And it is so widely used that it got its own syntax (the with statement)  
and library support (contextlib, for creating custom context managers). In  
any decent version of Python this idiom becomes:

with get(rname) as r:
   r.use

assuming get(rname) returns a suitable object (that defines __enter__ and  
__exit__)

>> def egor_read_file(fname, mode='rb'):
>>    print 'yes, master'
>>    try:
>> 	f = open(fname, mode=mode)
>>    except IOError:
>>        return (0, 'But, the file no open master!')
>>
>>    try:
>>        s = f.read()
>>    except NameError:
>>        return (0, 'the file still no open master!')
>>
>>    try:
>>        f.close()
>>    except:
>>        print 'That file sure is tricky master!
>>
>>    return (s, 'Whew! here is the file contents, master')
>
> What's above seems simpler. More important, if you do
> it this way then you _always_ have to check the return
> value of egor_read_file and take appropriate action -
> complicates the code everywhere the function is called
> as well as making the function more complicated.
> Doing it as in UseResource() above you don't need
> to worry about whether UseResource() failed
> _except_ in situations where you're certain that
> that's the right level to catch the error.

That's the standard argument showing why structured exceptions are a Good  
Thing. I'd say everyone should be aware of that, giving the ample usage of  
exceptions in Python, but looks like people requires a reminder from time  
to time.

-- 
Gabriel Genellina




More information about the Python-list mailing list