Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
Xeoth Avatar asked Oct 09 '20 18:10

Xeoth


4 Answers

You can use getattr:

getattr(getattr(foo, 'bar', None), 'baz', None)
like image 163
theEpsilon Avatar answered Oct 26 '22 14:10

theEpsilon


Most pythonic way is:

try:
    # do something
    ...
except (NameError, AttributeError) as e:
    # do something else
    ...
like image 44
soumya-kole Avatar answered Oct 26 '22 15:10

soumya-kole


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

{'foo': {'bar': 'baz'}}.get('foo', {}).get('bar')
like image 19
Aliaksandr Sushkevich Avatar answered Oct 26 '22 16:10

Aliaksandr Sushkevich


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

like image 10
Sérgio Rafael Siqueira Avatar answered Oct 26 '22 15:10

Sérgio Rafael Siqueira