[Python-Dev] 'With' context documentation draft (was Re: Terminology for PEP 343

Ron Adam rrr at ronadam.com
Fri Jul 15 21:55:44 CEST 2005


Michael Hudson wrote:
> "M.-A. Lemburg" <mal at egenix.com> writes:
> 
> 
>>This is exactly what I'm getting at: I can see the potential
>>use for resource management (which is what started out the
>>whole idea IIRC), but fail to see why you'd want to use it
>>for anything more complicated than that.
> 
> 
> I, as a concrete example, want to be able to write:
> 
> with output_to_file(f):
>     print stuff
>     function_that_prints_stuff()
> 
> and have the printed things end up in the file-like object f (in a
> single-threaded program, foom :)

I would like it to be that easy also.  However, it seems to me that 
using a context manager within try-except blocks will be a very common 
practice.

     try:
        with some_context() as var:
            <do stuff>
     except:
        <flag, log, and/or handle error>
     else:
        <everything is ok>

The context manager will handle it's own cleanup, but we will still (in 
most cases) need to react to the raised exception somehow (and 
someplace) even if it's with a pass.

It makes me think that the 'with' would be better expressed as a 
variation of a try statement.  And the documentation for the 'with' 
statement would then be grouped and explained along with the try statements.

Possibly:

     try with some_context() as VAR:
         <do stuff with VAR>
     except:                             # optional except-else?
         <react to error in context>
     else:
         <good to go>


or just:

     trywith some_context() as VAR:      # May cause an exception
         <do stuff with VAR>             # that needs to be caught.


I guess my point is: Since it's an encapsulated try-finally with a 
definite chance of generating an exception, Having a stronger 
association to 'try' in both the syntax and the documentation may be good.

Cheers,
Ron



More information about the Python-Dev mailing list