Which idiom is better? try: ... except Attr..Err or hasattr?

Tim Peters tim_one at email.msn.com
Thu Jan 27 03:34:37 EST 2000


[Peter Funk]
> Look at the following coding alternatives often seen in generic
> python code:
>
> class A:
>     def load(self):
>         # ... do something e.g. load a file
>         try:
>             self.update()
>         except AttributeError:
>             pass
>
> class B:
>     def load(self):
>         # ... do something e.g. load a file
>         if hasattr(self, 'update'):
>             self.update()
>
> Which coding idiom is better?  The second form is one line
> shorter than the first, but it has the disadvantage, that
> the method (or attribute) must be named twice. ...

I prefer the second form.  The first form is risky, because the try/except
can hide more than the author intended (that is, if self.update does exist,
any AttributeError raised during its execution will also get ignored).  I
don't care at all about the measly line or two, or duplicating a name (an
editor with word completion renders that trivial); but *do* care that the
*intent* of the first form is easier to see at a glance.  Alas, it doesn't
really mean what it appears to say.

exceptions-are-exceptionally-exceptional-ly y'ts  - tim






More information about the Python-list mailing list