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

Peter Funk pf at artcom-gmbh.de
Thu Jan 27 02:40:07 EST 2000


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.

Regards, Peter
-- 
Peter Funk, Oldenburger Str.86, 27777 Ganderkesee, Tel: 04222 9502 70, Fax: -60




More information about the Python-list mailing list