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

前端 未结 6 960
小鲜肉
小鲜肉 2021-01-07 17:07

My problem is a general one, how to chain a series of attribute lookups when one of the intermediate ones might return None, but since I ran into this problem t

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 17:39

    The most straightforward way is to wrap in a try...except 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.

提交回复
热议问题