Re Interest check in some delicious syntactic sugar for "except:pass"
Michael Rudolf
spamfresser at ch3ka.de
Wed Mar 3 09:50:19 EST 2010
Am 03.03.2010 12:47, schrieb Oren Elrad:
> """ code involving somefile """
> try:
> ........os.remove(somefile)
> except:
> .......pass # The bloody search indexer has got the file and I
> can't delete it. Nothing to be done.
You don't know that what you stated in your comment is true.
All you know is that there was an exception. To find the reason, you
have to inspect the exception.
You escpecially do NOT know whether the file is removed or not.
OK, os.remove() might be a CPython builtin (not sure ATM), but in
general all sort of crazy things can happen here, like ImportError
raised by code in the lib or so.
And of course: a bare except: also catches ^C or SystemExit. That is
almost certainly *not* what you want, right?
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 #dito1
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