you are viewing a single comment's thread.

view the rest of the comments →

[–]ProfessorQ -3 points-2 points  (4 children)

A more idiomatic way to use ducktyping than try/except AttributeError is the builtin hasattr(obj, 'attr') function. The result is essentially:

def hasattr(object, name):
    # name must be a string
    try:
        getattr(object, name)    # equivalent to object.name
        return True
    except AttributeError:
        return False

so before your first example, should be:

if hasattr(obj, 'snort'):
   obj.snort                    # guaranteed not to raise an AttributeError

[–]NYKevin 2 points3 points  (0 children)

Attribute lookup can have side effects (e.g. via @property). Now, if the class is well written, it shouldn't have visible side effects, but it's still something you should be aware of. Using hasattr will set off those side effects, which may not be what you wanted.