I ran into a case where this would be helpful again today, but for a reason I don’t think anybody brought up yet — the default argument.
Needing to access a specific nested attribute in structured data, where somewhere down the line, some of the attributes might start to be missing, because they’re only available under certain scenarios, the best implementation is using a try ... except block. I find this a bit overly verbose and unnecessary.
try:
some_flag = a.b.c.d.e.f.g
except AttributeError:
some_flag = False
In my case, I was already inside a try ... except block, which is what finally prompted me to propose a change / join a proposal discussion.
From a technical point of view, I think implementing nested access in getattr is a bit problematic, because, like it or not, even though they cannot be accessed via normal syntax, attributes can have dots in their name. On top of that, operator.attrgetter already exists, which implements nested access already, and isn’t such a critical component of the language.
I don’t really see any reason why operator.attrgetter, and for consistency operator.itemgetter, couldn’t get a default keyword argument, bringing it on-par with getattr’s functionality.
The main technical consideration here, I think, are which exceptions should they suppress. For operator.attrgetter, I think is pretty straight-forward — only AttributeError. For operator.itemgetter, I think it’s a fair a bit more common to possibly to encounter exceptions other than KeyError, but I think only suppressing KeyError is a very reasonable implementation choice.