0

我的目标是在我的程序遇到意外行为时引发 SystemExit 并记录错误。

我正在做类似的事情:

logger.error('Unexpected behaviour')
raise SystemExit

为了避免代码中的重复,我尝试编写一个装饰器来在每个 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)

所以我的问题是:我的装饰器是pythonic吗?如果不是,最好的 Pythonic 方式是什么?(我看到人们使用@something,但我不明白它的用法)。

谢谢!

4

1 回答 1

1

正如评论中提到的,你所做的并不是很装饰。这将是装饰:

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 只是您在声明函数时使用的语法糖。如果您使用在其他地方声明的函数/方法,这对您来说没有多大用处。

@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

我的装饰器是pythonic吗?

可以说,这并不是因为补丁很难看,它会增加意想不到的行为。更明确地说,您可以创建一个log_error_and_exit()函数或注册您自己的日志记录类,logging.setLoggerClass(OurLogger)也可以添加一个.fatal_error()方法。但是,我认为您的解决方案可以按原样进行。

于 2019-10-24T16:25:37.030 回答