Python上下文管理器到装饰器(反向)

时间:2016-07-08 10:52:11

标签: python decorator yield contextmanager

我想:

# Simple example, one could replace try/except by any other nested construct
def mycontextmanager_generator(foo):
    try:
        yield
    except:
        print 'bar'
        raise

mycontextmanager = build_contextmanager(mycontextmanager_generator)
mydecorator = build_decorator(mycontextmanager_generator)


>>> with mycontextmanager():
>>>     raise Exception('baz gone bar in context manager')
... bar


>>> @mydecorator()
>>> def bazzer():
>>>     raise Exception('baz gone bar in decorator')
>>> bazzer()
... bar

在这个例子中,我从生成器函数和同一函数的装饰器构建了一个上下文管理器。这是我试图以不成功的方式实现的目标。

更一般地说,我想要的是干:写一次try/except块,并通过装饰器上下文管理器重新使用再次:通过只编写一次的try / except bloc ,无论是在生成器函数还是任何其他包装器中。

ContextDecorator事物(py3中的contextlib / py2中的contextlib2)只能用于类,但在这种情况下它似乎没用......我错过了什么?有没有办法使用__enter____exit__使用基于类的ContextManager实现我的try / except块?

或者是否有可能将使用yield语法构建的上下文管理器转换为装饰器?

或者相反(decorator to contextmanager)?

如果不是,很高兴知道Python的限制是什么。

据我了解,yield语法与Python解释器和上下文切换紧密相关,我不知道是否有可能在该点上改变其行为。

2 个答案:

答案 0 :(得分:1)

通过组合contextmanager用于管理其上下文(_GeneratorContextManager)和ContextDecorator类的类,您可以轻松实现所需。例如

from contextlib import ContextDecorator, _GeneratorContextManager
from functools import wraps

class MyContextManager(_GeneratorContextManager, ContextDecorator):
    pass

def contextmanager(func):
    @wraps(func)
    def helper(*args, **kwds):
        return MyContextManager(func, args, kwds)
    return helper

@contextmanager
def print_bar_on_error():
    try:
        yield
    except:
        print('bar')
        raise

with print_bar_on_error():
    raise Exception('baz gone bar in context manager')

产生

bar
Traceback (most recent call last):
  File "run.py", line 28, in <module>
    raise Exception('baz gone bar in context manager')
Exception: baz gone bar in context manager

当用作装饰者时

@print_bar_on_error()
def bazzer():
    raise Exception('baz gone bar in decorator')
bazzer()

产生

bar
Traceback (most recent call last):
  File "run.py", line 32, in <module>
    bazzer()
  File "c:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "run.py", line 31, in bazzer
    raise Exception('baz gone bar in decorator')
Exception: baz gone bar in decorator
    return func(*args, **kwds)
Exception: baz gone bar in decorator

答案 1 :(得分:0)

比Dunes&#39;更容易理解的解决方案。一,尽管没有利用ContextDecorator双语法。

import contextlib
import functools

def handler():
    try:
        yield
    except:
        print 'bar'


my_contextmanager = contextlib.contextmanager(handler)


def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        with my_contextmanager():
            func(*args, **kwargs)
    return wrapper


with my_contextmanager():
    raise Exception('baz')

@my_decorator
def f():
    raise Exception('baz')

f()

给出:

bar
bar