[Python-Dev] With context, please

Aahz aahz at pythoncraft.com
Sat Apr 22 18:25:39 CEST 2006


On Sat, Apr 22, 2006, Phillip J. Eby wrote:
> At 09:05 AM 4/22/2006 -0700, Aahz wrote:
>>
>>I've been following the with/context discussion, not that closely, but
>>reading all the posts.  I also have to write docs on this for Python for
>>Dummies, which I think is going to be the first book out after 2.5.  So
>>far, my take is that I want the block of code to be executed in a
>>context.  I'm probably going to use that terminology no matter what gets
>>decided here -- I think it's the only sensible way to describe it for
>>newcomers.  Aside from that, I don't care all that much.
>>
>>(Actually, we just turned in the first draft, and I haven't talked about
>>context managers at all -- what I said was that EXPR returns a context.)
> 
> And what did you say that __context__ returns?

Whoops, I half-lied.  I forgot that my co-author did indeed mention
"context manager".

Here's the main part (sorry about the missing formatting):

    The syntax is as follows:

    with EXPRESSION as NAME:
        BLOCK

    The with statement works like this:  
    
    EXPRESSION returns a value that the with statement uses to create a
    context (a special kind of namespace).  The context is used to
    execute the BLOCK.  The block might end normally, get terminated by
    a break or return, or raise an exception. No matter which of those
    things happens, the context contains code to clean up after the
    block.

    The as NAME part is optional.  If you include it, you can use NAME
    in your BLOCK

Then a bit later:

    The protocol used by the with statement is called the context
    management protocol, and objects implementing it are context
    managers.

However, we do not talk at all about __context__(), __enter__(), or
__exit__() -- we decided that was too advanced for our audience, we
simply wanted to give them the bare basics of using `with`.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Argue for your limitations, and sure enough they're yours."  --Richard Bach


More information about the Python-Dev mailing list