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
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()