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

Michael Hudson mwh21 at cam.ac.uk
Thu Jan 27 03:47:55 EST 2000


pf at artcom-gmbh.de (Peter Funk) writes:

> 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.  Both idioms are used in the standard libary.

The usual response is that you use the former if you only expect the
attribute look up to fail rarely ("exceptionally") and the latter if
you expect it to fail regulalarly.

There's also this approach:

class C:
    def __init__(self):
        up = getattr(self,"update",None)
        if up is not None: up()

This depends on Python 1.5.2 (I think) so that could be one reason it
doesn't crop up much in the standard library. It looks a bit odd to
me, not sure why.

I tend to use one of the first two depending on my mood.

Cheers,
Michael



More information about the Python-list mailing list