用内部函数的返回值调用外部函数的返回值,而不检查内部函数的返回值

问题描述 投票:-1回答:1

考虑以下装饰器:

def wraper(function):
    @wraps(function)
    def wrap(*args,**kwargs):
        if function(*args, **kwargs):
             return function(*args, **kwargs)
        else:
            response = JsonResponse()
            response.status_code = 500
            return response 
        return wrap

装饰功能:

@wraper
def function(1):
    var = None
    try:
       var = 1            #Consider somehow an exception is raised
    except Exception as e:
       print(e)
    return var  

考虑其他功能:

def function2():
    print("In function")
    variable = function()  # Assign the variable and proceed normally or return from function2,
                           # with the JsonResponse in case of an exception
    print("Returning from function2")
    return variable

如果返回JsonResponse,我希望函数2的输出为:

In function

以及以下内容,如果一切正常:

In function

Returnning from function2

注意:我希望从修饰函数返回的值是function2的返回值,以防引发异常。在另一种情况下,(当引发异常时)我只想返回JsonResponse,而不执行任何function2的代码

python python-3.x function return python-decorators
1个回答
0
投票

您定义的装饰器从不返回任何内容。您错过了最后一行的回报。

def wraper(function):
    @wraps(function)
    def wrap(*args,**kwargs):
        result = function(*args, **kwargs)
        if result:
            return result
        else:
            response = JsonResponse()
            response.status_code = 500
            return response
    return wrap

如果装饰的函数返回False或等效值,则上面的装饰器将返回响应。否则,它将返回装饰函数返回的内容。

如果您只是想知道function是否返回没有错误,请执行以下操作:

def function():
    # Code that can crash goes here
    return 0 # return value if no errors were found

def function2():
    print("In function")
    try:
        variable = function()
    except Exception: # If an error occurs return the response
        response = JsonResponse()
        response.status_code = 500
        return response
    print("Returning from function2")
    return variable # If everything went well return the value from function

并且请删除所有装饰器。对于这些用例,您不需要它们。

© www.soinside.com 2019 - 2024. All rights reserved.