简体   繁体   English

用于完成功能的Python装饰器

[英]Python decorator for function completion

Is it possible to develop a decorator to determine if a function successfully completed without crashing ? 是否有可能开发一个装饰器来确定功能是否成功完成而不崩溃? Something like the decorator below but it must detect if the function ran successfully. 类似于下面的装饰器,但它必须检测该函数是否成功运行。

def functionStartDecorator():
    print("Function has started")
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            #Todo log function has run
            return functionToBeDecorated(*args, **kwargs)
        return wrapper
    return decoratorWrapper  

As said in comments, simplest would be to wrap your function in a try/except. 如评论中所述,最简单的方法是将您的函数包装在try / except中。 If your function returns nothing and simply operate by side-effect, it should be straightforward to have the decorated function return the status of that function run: 如果您的函数什么也不返回,并且仅通过副作用进行操作,那么让修饰过的函数返回该函数的运行状态应该很简单:

def tryfn(f):
    def decorated(*args, **kwargs):
        try:
            f(*args, **kwargs)
            return 'Ran successfully'
        except Exception as e:
            return 'Error: {}'.format(e)
    return decorated

You can then tweak the exact return type of decorated: maybe return a boolean, maybe append the status of the function to the return of f , maybe log things... The core principle will probably still be around a try/except within the decorated function. 然后,您可以调整修饰的确切返回类型:可能返回一个布尔值,也许将函数的状态附加到f的返回上,也许会记录一些东西...核心原理可能仍然围绕try/except ,功能。 For instance, if you want to return both your return value (or None if it failed) and whether this was a success: 例如,如果您想同时返回自己的返回值(如果失败,则返回None )以及是否返回成功:

def tryfn(f):
    def decorated(*args, **kwargs):
        try:
            res = f(*args, **kwargs)
            return True, res
        except:
            return False, None
    return decorated

Note that in this case, you're losing the information about the exact error, so you might want to expand the return to include success, failure, error, etc... that becomes a trade-off between convenience and completeness, which will depend on your exact problem. 请注意,在这种情况下,您将丢失有关确切错误的信息,因此您可能希望将收益范围扩大到包括成功,失败,错误等……这将在便利性和完整性之间进行权衡,这将使取决于您的确切问题。

I did something like this. 我做了这样的事情。 Do you see any issues with this code ? 您认为此代码有任何问题吗?

def functionStartDecorator():
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            try:
                print("Function has started")
                result=functionToBeDecorated(*args, **kwargs)
                print("Function has complete")
                return result
            except:
                print ("Function failed")
        return wrapper
    return decoratorWrapper  

@functionStartDecorator()
def simplefunc():
    return "somthing"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM