Is except: ... pass bad style?

Michael Hudson mwh at python.net
Thu Sep 9 18:45:16 CEST 2004


marduk <marduk at python.net> writes:

> I commonly use code like this
> 
> try:
>     # call optional method
>     myobj.method()
> except AttributeError:
>     # no biggie
>     pass
> 
> 
> Occasionally I use pylint, which is a good tool, but in the above
> snippet pylint will complain that 'Except doesn't do anything'.  True,
> but is that bad style?  I know there are other ways of doing it, but
> of all the other "obvious" ones, this appears the most straight
> forward.

Sounds like a dubious warning to me.

> Should I ignore pylint or is there a more Pythonic way to do this?

Well, 

try:
    meth = myobj.method
except AttributeError:
    pass
else:
    meth()

is possibly better (your version might hide bugs in the method).  It's
a pain to do this all the time, though.

Come to think of it

getattr(myobj, "method", lambda :None)()

also acheives the same thing.  Bit inscrutable, though.

Cheers,
mwh

-- 
  <thirmite> what's a web widget??
  <glyph> thirmite: internet on a stick, on fire
  <Acapnotic> with web sauce!                   -- from Twisted.Quotes



More information about the Python-list mailing list