Optional chaining in Python

Optional chaining in Python

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
    ...

Optional chaining in Python

If its a dictionary you can use get(keyname, value)

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

Leave a Reply

Your email address will not be published. Required fields are marked *