Search code examples
pythonidiomsternary

self-referencing ternary


I've been doing this for a while:

x = x if x else y

In all sorts of contexts where x might be None, False, 0, '', [], or {}.

I know the purists would rather I:

if not x:
    x = y

but forget that, that's not my question. My question is:

Is there anything 'wrong' with x = x if x else y besides the fact it's a ternary? Specifically, is it ok to have a ternary self-assign like that.

NOTE

My qustion is not is x = x if C else y ok. I know it is.

Many thanks


Solution

  • There is nothing wrong with using ternary for x = x if c else y, however, in the case of x = x if x else y the logic really does just reduce to

    x = x or y
    

    This is because in Python x or y evaluates to 'if x is false, then y, else x'

    So x if x else y == y if not x else x == x or y

    Obviously, x or y is the clearest and should be used.