Search code examples
python-3.xreturnreturn-valuereturn-typenonetype

Is `return` alone equivalent to `return(None)` in Python 3.8?


I just saw the following Python code, and I'm a bit confused by the first return. Does it return None by default? Is it equivalent to return(None)? If the first return is executed, will the function inner() automatically end there and the second return be left alone?

def smart_check(f):
    def inner(a,b):
        if b==0:
            print("illegit: b =", b)
            return   # the first return
        return(f(a,b))
    return(inner)

@smart_check
def divide(a,b):
    return(a/b)

Solution

  • Does it return None by default? Is it equivalent to return(None)

    Yes, see docs: If an expression list is present, it is evaluated, else None is substituted.

    If the first return is executed, will the function inner() automatically end there and the second return be left alone?

    Yes


    If you don't want to return anything you can even drop the return statement completely:

     def smart_check(f):
        def inner(a,b):
            if b != 0:
                return f(a,b)
            print("illegit: b =", b)
        return(inner)
    

    As print doesn't return anything you could even rewrite this function as

    def smart_check(f):
       def inner(a,b):
           return f(a,b) if b!=0 else print("illegit: b =", b)
       return(inner)