[Python-Dev] exec/with thunk-handling proposal (on a new thread eventually)

holger krekel pyth@devel.trillke.net
Mon, 3 Feb 2003 18:46:22 +0100


Aahz wrote:
> [holger krekel]
> >
> >     def __enter__(self):  
> >         "before suite start"
> > 
> >     def __except__(self, type, value, tb): 
> >         "swallow given exception, reraise if neccessary"
> > 
> >     def __leave__(self):
> >         """upon suite finish (not called if __except__ 
> >            exists and an exception happened)
> >         """
> 
> No, __leave__/__exit__ should always be called regardless of whether an
> exception hits.  That's the whole point of this proposal, IMO.

The __except__ hook (like all others) is optional.  Always invoking 
__except__ and __leave__ would amount to a try-except-finally clause 
which is seldomly needed and not existing today.  

Most often you either have exception handling or finally-handling.  
Anyway, it is no problem to invoke __leave__ from within __except__ if 
this is really neccessary (it hasn't been with my use cases). 
And __leave__ does get invoked if there is no __except__.

> > One remark (mainly to Michael as he does that other 
> > patch) about the hook-name __leave__ versus __exit__.
> > we may want to eventually allow 'yield' within the
> > thunk and then '__exit__' would be misleading.  Here is
> > the use case:
> > 
> >     exec self.mylock:   # would lock/unlock on entering/leaving 
> >                         # the generator
> >         ...
> >         for whatever in something:
> >             yield whatever  
> >         ...
> 
> I'm thinking that this is *way* too complex.

If yield would be allowed inside try-finally then this 
would be straight forward IMO.  Obviously, today there is
a semantic problem because it is unclear if the finally-code
should be executed multiple times.  

But with the exec/with proposal this can be cleanly 
defined from the start (enter/leave) *just in case* 
that we ever want to allow yield within the new 
thunk-construct.  

Actually, I am just arguing that the "finish" hook should be 
named '__leave__' rather than '__exit__' because the latter
sounds like "completly finished".  I don't think it hurts even
if we never allow yield within try-finally.

regards,

    holger