0

我正在尝试编写一个可以与with关键字一起使用的装饰器。

# regular code ...
with my_exception_handler():
    # dangerous code ...
# regular code ...

my_exception_handler 将接收一个函数并将其包装在一个巨大的 try-except 中。

我想让它成为一个装饰器/包装器,因为它有很多我不想复制粘贴的代码。我不知道从哪里开始。我编写了一个常规装饰器,它适用于函数,但不适用于中间代码块。

4

3 回答 3

5

与 , 一起使用的东西with是上下文管理器而不是装饰器——它们是两个完全不同的东西。

编辑:请参阅 kindall 的帖子,了解如何编写简单的上下文管理器而无需使用成熟的类;我没有时间用这样的例子来修改我的答案:)

于 2013-09-29T17:54:08.867 回答
2

You need to write a context manager, not a decorator. You can very easily do what you want to do using the contextlib.contextmanager decorator.

from contextlib import contextmanager

@contextmanager
def my_exception_handler():
     try:
         yield          # execute the code in the "with" block
     except Exception as e:
         # your exception-handling code goes here
         print e

# try it out
with my_exception_handler():
    raise ValueError("this error has value")
于 2013-09-29T18:39:52.553 回答
0

在了解了上下文管理器之后,我使用了一个扩展的回溯功能,并将其变成了一个装饰器和一个上下文管理器,下面有几个片段:

def traceback_decorator(function):

    def wrap(*args, **kwargs):

        try:
            return function(*args, **kwargs)
        except:
            print_exc_plus()


def traceback_wrapper(function=None, *args, **kwargs):

    context = _TracebackContext()

    if function is None:
        return context

    with context:
        function(*args, **kwargs)

class _TracebackContext(object):

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            print_exc_plus()
于 2013-09-29T18:20:56.997 回答