A shorter way to express it? C = A if A else B

I repeat a lot:

val = x if x else y

Sometimes xseveral levels go deep into a class or a dictionary, so it becomes very long:

val = obj.elements[0].something if obj.elements[0].something else y

It looks ugly and makes me type a lot more. Any known ways to shorten this? Perhaps such a built-in built-in?

val = first_try(x, y)

I think I could easily write my own, but was hoping for a built-in version.

first_try = lambda x,y: x if x else y
+3
source share
3 answers

The operator orreturns the first argument, which is converted to True:

val = x or y

eg:.

>>> None or 'OK'
'OK'
+16
source

It seems to me like trying to make the code too concise. I would probably do something like this:

x = a.b.c.d[0]
val = x if x else y

, .

+1

getattr default. :

val = getattr(obj.elements[0], 'something', y)
0

Source: https://habr.com/ru/post/1776807/


All Articles