Javascript has a useful pattern called optional chaining, that lets you safely traverse through a deeply nested object without key errors.
For example:
const foo= {
correct: {
key: 'nested'
}
}
const correct = foo?.correct?.key
const incorrect = foo?.incorrect?.key
You can also do it the old fashioned way like this:
const nested = foo && foo.bar && foo.bar.key
Does Python have a pattern as clean as this for traversing nested dictionaries? I find it particularly verbose when traversing deeply nested objects with long key names.
This is the closest I can get in Python:
getattr(getattr(foo, 'correct', None), 'key', None)
Which is pretty gross and starts getting dumb beyond two or three nestings