'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 1:[1]
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
Solution 2:[2]
With the := operator, your Python example can be made a little more concise.
if not (x := f(y)):
return APPROPRIATE_ERROR
After this, assuming the condition wasn't met, you can use x as normal.
There are a number of places where this becomes useful. I find it especially useful in writing lambdas, where I can't do a normal assignment but don't want to recalculate a value repeatedly.
Solution 3:[3]
Im adding this just for fun (and to elaborate on my comment). You can take the hacky decorator approach from the second answer from here. For completeness:
class ReturnValue(Exception):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def enable_ret(func):
def decorated_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except ReturnValue as exc:
return exc.value
return decorated_func
def ret(value):
raise ReturnValue(value)
Now, remember that if and while blocks are exceptions in the scoping rules. Specifically, variables defined within an if or while block are available in the scope of the function. If I understood your question correctly, you could now use this like so:
@enable_ret
def testfunc(x):
# Return None if y is false
ret(None) if not (y := x) else 0
# Otherwise we continue (and can access y) here
print(y)
return 1
Please dont do this though :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kaia |
| Solution 2 | Chris |
| Solution 3 | Banana |
