Is is possible to return from a method in single line in python
Looking for something like this
return None if x is None
Tried abov
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)
You could also try the list[bool]
expression:
return [value, None][x == None]
Now if the second bracket evaluates to true, None is returned otherwise, the value you want to return is returned
It is possible to write a standard "if" statement on a single line:
if x is None: return None
However the pep 8 style guide recommends against doing this:
Compound statements (multiple statements on the same line) are generally discouraged
Yes, it's called a conditional expression:
return None if x is None else something_else
You need an else something
in a conditional for it to work.