57

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 above, and it is invalid syntax

I could easily do:

if x is None:
    return None

But just curious if I can combine above if statement into a single line

Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
user462455
  • 12,838
  • 18
  • 65
  • 96

4 Answers4

88

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.

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 4
    But it's not clear that OP wants to return `False` if x is not `None`. – kojiro Sep 07 '13 at 05:18
  • What if the calling function expects a string? ;) – thefourtheye Sep 07 '13 at 05:19
  • 4
    Remember before PEP 308 when we had to emulate the ternary with an array? `return [False,None][x is None]`? Me neither… *runs away* – kojiro Sep 07 '13 at 05:21
  • 10
    I'm pretty sure the function isn't supposed to return at all in the else case. – user2357112 Sep 07 '13 at 05:22
  • 8
    Functions in Python always return an implicit None if they lack an explicit return. – Paulo Scardine Sep 07 '13 at 06:00
  • 5
    Clarification: The function isn't supposed to return *from that line* in the else case; it's supposed to keep executing. – user2357112 Sep 07 '13 at 06:38
  • @hus787 I'd like to clarify that `False` was just something I added. Of course, the OP could easily replace it with whatever he needs to return. It was not meant to be anything. Infact, I'll change it – TerryA Sep 07 '13 at 08:46
  • @Haidro it's not about returning `False` or `something_else` it's about the assumption that OP definitely wants the function to terminate and return at that point, which strictly speaking is not mentioned in the question. Maybe OP wants the function to proceed with something *else* if the condition is negative. – Bleeding Fingers Sep 07 '13 at 09:52
  • @AshwiniChaudhary Is this expression and accepted expression are same? I don't think so. It looks same as `return test ? true_express : false_expression;` in C – Grijesh Chauhan Sep 18 '13 at 05:41
  • 1
    @GrijeshChauhan Yes, they are not same. An `else` is required in the accepted expression to make them identical. – Ashwini Chaudhary Sep 18 '13 at 05:45
  • NOTE to clarify: You can only use the `return` operator once in a ternary expression. The following will not work: return `"Yes" if value >= True else return "No"` – Bryan Dimas Oct 21 '15 at 21:05
  • @BryanDimas `return "yes" if value else "No"` – Fraser Apr 08 '18 at 07:53
  • 1
    No, I think the idea is to do a conditional return (return only if condition is met). Your solution will always return. – Leo Ufimtsev May 02 '19 at 13:15
81

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

nakedfanatic
  • 3,108
  • 2
  • 28
  • 33
  • 5
    I would humbly argue that "if EXPR: return" is a permissible exception. The reason is that when debugging, "if EXPR: func()" (as per pep 8 example), it's not clear if func() was called or not. However when "if EXPR: return" is called, then we know EXPR was true because return exits the function. – Leo Ufimtsev May 02 '19 at 13:26
8

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)
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • 3
    This is definitely not how you should do things, as you say, but I thought it was a little clever at least. – kqr Sep 07 '13 at 09:05
  • @kqr: I like to combine fashionable things (function decorators) with deeply unfashionable things (exceptions as non-error flow control) ;-) But the main point is to illustrate that `return` isn't an expression, so the only way to use an expression to get out of a function is to throw something. Or a `yield`-expression, but that's not generally applicable. – Steve Jessop Sep 07 '13 at 09:07
  • This is a inverse answer, like a "Not False" kinda answer. It explains why one should not do something. Thank you for posting this, quite a creative aproach to things. I enjoyed reading it over my cup of morning coffee. – Leo Ufimtsev May 02 '19 at 13:19
7

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

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 4
    This is silly when ternary expressions are possible. It made sense to do this before they existed, but now there's absolutely no reason to. – Anorov Sep 07 '13 at 08:05
  • 3
    +1 Helped me realize that you can ONLY use the `return` operator ONCE in a ternary expression. `return "Yes" if value == True else "No"` will return "No" in the else statement. – Bryan Dimas Oct 21 '15 at 21:00