Search code examples
pythonconditional-operator

Is there a Python one-line idiom like x = y or return?


The return early pattern is an alternative to nested if/else statements. In Ruby this is sometimes see as one line:

# Ruby
x = f(y) or return APPROPRIATE_ERROR

It will return if the expression on the left of or is falsey.

Is there a Python way of doing this?, other than

# Python
x = f(y)
if not x:
    return APPROPRIATE_ERROR

Solution

  • It's syntactically correct to do

    ...
    if not (x := f(y)): return APPROPRIATE_ERROR
    ...
    

    Generally, it's not recommended as standard style, but the option is there if you like it