How to chain attribute lookups that might return None in Python?

The most straightforward way is to wrap in a tryexcept block.

try:
    title = soup.head.title.string
except AttributeError:
    print "Title doesn't exist!"

There’s really no reason to test at each level when removing each test would raise the same exception in the failure case. I would consider this idiomatic in Python.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)