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')
You can use the Glom.
from glom import glom
target = {'a': {'b': {'c': 'd'}}}
glom(target, 'a.b.c', default=None) # returns 'd'
https://github.com/mahmoud/glom
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With