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

前端 未结 4 973
迷失自我
迷失自我 2020-12-09 07:36

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

相关标签:
4条回答
  • 2020-12-09 08:02

    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)
    
    0 讨论(0)
  • 2020-12-09 08:02

    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

    0 讨论(0)
  • 2020-12-09 08:08

    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

    0 讨论(0)
  • 2020-12-09 08:22

    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.

    0 讨论(0)
提交回复
热议问题