I find myself repeating this a lot:
val = x if x else y
Sometimes x goes several levels deep into a class or dictionary so it gets very long:
val = obj.elements[0].something if obj.elements[0].something else y
It looks ugly and forces me to type a lot more. Any known ways to shorten this? Perhaps a builtin like this exists?
val = first_try(x, y)
I guess I could easily write my own but was hoping for a built in.
first_try = lambda x,y: x if x else y
The
oroperator returns the first argument that converts to True:E.g.: