Is it possible to write single line return statement with if statement?

Question:

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

Asked By: user462455

||

Answers:

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.

Answered By: TerryA

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

Answered By: nakedfanatic

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

Answered By: smac89

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)
Answered By: Steve Jessop
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.