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

前端 未结 6 959
小鲜肉
小鲜肉 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:28

    This is how I handled it with inspiration from @TAS and Is there a Python library (or pattern) like Ruby's andand?

    class Andand(object):
        def __init__(self, item=None):
            self.item = item
    
        def __getattr__(self, name):
            try:
                item = getattr(self.item, name)
                return item if name is 'item' else Andand(item)
            except AttributeError:
                return Andand()     
    
        def __call__(self):
            return self.item
    
    
    title = Andand(soup).head.title.string()
    

提交回复
热议问题