A "scopeguard" for Python

Michael Rudolf spamfresser at ch3ka.de
Thu Mar 4 12:50:32 EST 2010


Am 04.03.2010 18:20, schrieb Robert Kern:
>
> What I'm trying to explain is that the with: statement has a use even if
> Cleanup doesn't. Arguing that Cleanup doesn't improve on try: finally:
> does not mean that the with: statement doesn't improve on try: finally:.

Yes, the with-statement rocks :)

I suggested such a thing a few days ago in another thread, where OP 
wanted a "silent" keyword like:

silent:
	do_stuff()

would be equivalent to:
try: do_stuff() except: pass

Of course catching *all* exceptions was a bad idea, so I came up with 
the code below and now I actually like it and use it myself :)

---------snip---------
To your first question about a "silenced" keyword: you could emulate 
this with context managers I guess.

Something like (untested, just a quick mockup how it could look):



class silenced:
     def __init__(self, *silenced):
         self.exceptions=tuple(silenced) #just to be explicit
     def __enter__(self):
         return self            #dito
     def __exit__(self, type, value, traceback):
         for ex in self.exceptions:
             if isinstance(value, ex):
                 return True #supresses exception


So:

with silenced(os.Error):
     os.remove(somefile)

Would translate to:

try:
     os.remove(somefile)
except os.Error:
     pass

One nice thing about this approach would be that you can alias a set of 
exceptions with this:

idontcareabouttheseerrors=silenced(TypeError, ValueError, PEBCAKError, 
SyntaxError, EndOfWorldError, 1D10T_Error)

with idontcareabouttheseerrors:
     do_stuff()

Regards,
Michael



More information about the Python-list mailing list