[Python-Dev] anonymous blocks (don't combine them with generator finalization)

Josiah Carlson jcarlson at uci.edu
Fri Apr 22 02:59:59 CEST 2005


Guido van Rossum <gvanrossum at gmail.com> wrote:
> 
> [Brett]
> > I think I agree with Samuele that it would be more pertinent to put all of this
> > effort into trying to come up with some way to handle cleanup in a generator.
> 
> I.e. PEP 325.
> 
> But (as I explained, and you agree) that still doesn't render PEP 310
> unnecessary, because abusing the for-loop for implied cleanup
> semantics is ugly and expensive, and would change generator semantics;
> and it bugs me that the finally clause's reachability depends on the
> destructor executing.

Yes and no.  PEP 325 offers a method to generators that handles cleanup
if necessary and calls it close().  Obviously calling it close is a
mistake.  Actually, calling it anything is a mistake, and trying to
combine try/finally handling in generators with __exit__/close (inside
or outside of generators) is also a mistake.


Start by saying, "If a non-finalized generator is garbage collected, it
will be finalized."  Whether this be by an exception or forcing a return,
so be it.

If this were to happen, we have generator finalization handled by the
garbage collector, and don't need to translate /any/ for loop.  As long
as the garbage collection requirement is documented, we are covered (yay!).


What about ...

i.__enter__()
try:
    ...
finally:
    i.__exit__()

... types of things?  Well, you seem to have offered a syntax ...

[VAR '=']* EXPR:
    BODY

... which seems to translate into ...

[VAR = ] __var = EXPR
try:
    BODY
finally:
    __var.__exit__()

... or something like that.  Great!  We've got a syntax for resource
allocation/freeing outside of generators, and a non-syntax for resource
allocation/freeing inside of generators.


 - Josiah



More information about the Python-Dev mailing list