[Python-Dev] anonymous blocks

Brett C. bac at OCF.Berkeley.EDU
Fri Apr 22 06:26:00 CEST 2005


Guido van Rossum 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;

Right, I'm not saying PEP 310 shouldn't also be considered.  It just seems like
we are beginning to pile a lot on this discussion by bringing in PEP 310 and
PEP 325 in at the same time since, as pointed out, there is no guarantee that
anything will be called in a generator and thus making PEP 310 work in
generators does not seem guaranteed to solve that problem (although I might
have missed something; just started really following the thread today).

At this point anonymous blocks just don't seem to be happening, at least not
like in Ruby.  Fine, I didn't want them anyway.  Now we are trying to simplify
resource cleanup and handling.  What I am trying to say is that generators
differ just enough as to possibly warrant a separate discussion from all of
this other resource handling "stuff".

So I am advocating a more focused generator discussion since resource handling
in generators is much more difficult than the general case in non-generator
situations.  I mean obviously in the general case all of this is handled
already in Python today with try/finally.  But with generators you have to jump
through some extra hoops to get similar support (passing in anything that needs
to be cleaned up, hoping that garbage collection will eventually handle things,
etc.).

> and it bugs me that the finally clause's reachability depends on the
> destructor executing.
> 

Yeah, I don't like it either.  I would rather see something like:

 def gen():
    FILE = open("stuff.txt", 'rU')
    for line in FILE:
        yield line

    cleanup:
        FILE.close()

and have whatever is in the 'cleanup' block be either accessible from a method
in the generator or have it become the equivalent of a __del__ for the
generator, or maybe even both (which would remove contention that whatever
needs to be cleaned up is done too late thanks to gc not guaranteeing immediate
cleanup).  This way you get the guaranteed cleanup regardless and you don't
have to worry about creating everything outside of the generator, passing it
in, and then handling cleanup in a try/finally that contains the next() calls
to the generator (or any other contortion you might have to go through).

Anyway, my random Python suggestion for the day.

-Brett


More information about the Python-Dev mailing list