Is except: ... pass bad style?

Donn Cave donn at u.washington.edu
Thu Sep 9 16:07:13 EDT 2004


In article <m33c1rcrxg.fsf at pc150.maths.bris.ac.uk>,
 Michael Hudson <mwh at python.net> wrote:
...
> 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.

Along the same lines,

  if hasattr(myobj, 'method'):
      myobj.method()

That's not uncommon usage, and has the advantage
of more directly and economically saying what the
try/except block is trying to say.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list