Disclaimer: don't actually do this. If you really want a one-liner then like nakedfanatic says just break the rule of thumb from PEP-8. However, it illustrates why return
isn't behaving as you thought it might, and what a thing would look like that does behave as you thought return
might.
The reason you can't say return None if x is None
, is that return
introduces a statement, not an expression. So there's no way to parenthesise it (return None) if x is None else (pass)
, or whatever.
That's OK, we can fix that. Let's write a function ret
that behaves like return
except that it's an expression rather than a full statement:
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)
@enable_ret
def testfunc(x):
ret(None) if x is None else 0
# in a real use-case there would be more code here
# ...
return 1
print testfunc(None)
print testfunc(1)