Optional chaining in Python

In JavaScript, if I'm not sure whether every element of the chain exists/is not undefined, I can do foo?.bar, and if bar does not exist on foo, the interpreter will silently short circuit it and not throw an error.

Is there anything similar in Python? For now, I've been doing it like this:

if foo and foo.bar and foo.bar.baz:
    # do something

My intuition tells me that this isn't the best way to check whether every element of the chain exists. Is there a more elegant/Pythonic way to do this?


You can use getattr:

getattr(getattr(foo, 'bar', None), 'baz', None)

Most pythonic way is:

try:
    # do something
    ...
except (NameError, AttributeError) as e:
    # do something else
    ...

If it's a dictionary you can use get(keyname, value)

{'foo': {'bar': 'baz'}}.get('foo', {}).get('bar')