on-internet
← Community

Optional chaining for Python objects: foo?.bar?.baz

Stack Overflow ·

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?

Comments

Sign in or sign up to comment and upvote.

No comments yet.