简体   繁体   English

编写我的装饰器的 Pythonic 方式是什么?

[英]What is the pythonic way to write my decorator?

My objective is to raise SystemExit and log the error when my program encounter an unexpected behavior.我的目标是在我的程序遇到意外行为时引发 SystemExit 并记录错误。

I was doing something like:我正在做类似的事情:

logger.error('Unexpected behaviour')
raise SystemExit

In order to avoid the repetition in my code i tried to write a decorator to raise SystemExit at each logger.error call:为了避免我的代码中的重复,我尝试编写一个装饰器来在每个 logger.error 调用时引发 SystemExit:

error = logger.error
def error_from_logger(msg) :
    ''' Decorator for logger.error to kill the program at the call '''

    error(msg)
    raise SystemExit

logger.error = error_from_logger
del(error_from_logger)

So my question is: Is my decorator pythonic?所以我的问题是:我的装饰器是 pythonic 吗? And if not what is the best pythonic way to write it?如果不是,最好的 Pythonic 编写方式是什么? (I saw people use @something but I don't understand it's usage). (我看到人们使用@something 但我不明白它的用法)。

Thanks!谢谢!

As has been mentioned in the comments, what you have done isn't quite decorating.正如评论中提到的,你所做的并不是很装饰。 This would be decorating:这将是装饰:

def call_then_exit(func):
    def called_and_exited(*args, **kwargs):
        func(*args, **kwargs)
        raise SystemExit
    return called_and_exited

logger = logging.getLogger()
logger.error = call_then_exit(logger.error)  # this is the decoration

logger.error("some error has happened")  # prints the message and exists

@decorator is just syntactic sugar which you use when declaring a function. @decorator 只是您在声明函数时使用的语法糖。 This isn't much use to you if you are using a function/method declared elsewhere.如果您使用的是在别处声明的函数/方法,这对您没有多大用处。

@call_then_exit  # this is the decoration
def say_hi():
    print('hello')

say_hi()  # prints 'hi' and exits
print('did we exit?')  # we never reach this

Is my decorator pythonic?我的装饰器是 pythonic 吗?

Arguably it is not because patching is ugly and it adds unexpected behaviour.可以说,这并不是因为修补很丑陋,而且会增加意想不到的行为。 To be more explicit, you could make a log_error_and_exit() function or register your own logging class with logging.setLoggerClass(OurLogger) and maybe add a .fatal_error() method.更明确地说,您可以创建一个log_error_and_exit()函数或使用logging.setLoggerClass(OurLogger)注册您自己的日志记录类,并且可能添加一个.fatal_error()方法。 However, I think your solution is OK as-is.但是,我认为您的解决方案按原样可以。

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

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