Which idiom is better? try: ... except Attr..Err or hasattr?
Laurence Tratt
tratt at dcs.kcl.ac.uk
Thu Jan 27 04:38:17 EST 2000
Peter Funk wrote:
> 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.
As a general rule, I would always use the second form: your intent - that
you're not sure if update exists - is much clearer.
However, if update nearly always exists, the second form is slower because
it has to perform the lookup for update twice; if update rarely exists then
the overhead in raising the exception causes the first form to be much
slower. In practice this is rarely important unless you have a long loop,
and need to squeeze every last ounce out of the interpreter.
To give you a quick idea, I tried a little script, and the rough figures
suggest that with a small dictionary, if update exists the first form is
about x2 faster than the second; if update doesn't exist the second form is
about x4 - x6 faster. So the difference isn't that much, unless you make the
same call a lot of times.
Laurie
More information about the Python-list
mailing list