【发布时间】:2014-10-01 04:40:01
【问题描述】:
我有一个帮助器类 Decontext,我用它来将上下文管理器变成装饰器(pyton 2.6)。
class Decontext(object):
"""
makes a context manager also act as decorator
"""
def __init__(self, context_manager):
self._cm = context_manager
def __enter__(self):
return self._cm.__enter__()
def __exit__(self, *args, **kwds):
return self._cm.__exit__(*args, **kwds)
def __call__(self, func):
def wrapper(*args, **kwds):
with self:
return func(*args, **kwds)
return wrapper
我的contextmanager 接受了一个参数,我想弄清楚在使用这个装饰器时如何传递这个参数?
@contextmanager
def sample_t(arg1):
print "<%s>" % arg1
yield
这就是我使用它失败的方式:
my_deco = Decontext(sample_t)
@my_deco(arg1='example')
def some_func()
print 'works'
编辑:
我希望Decontext 类在__call__ 函数执行时传递context_manager 中的所有*args。
例子:
decorator_example = Decontext(sample_t) // I don't want to pass in the argument here but when the decorator is created. How can I modify my class to make this enhancement
编辑 2:
我所期望的示例
my_deco = Decontext(sample_t)
@my_deco(arg1='example')
def some_func()
print 'works'
预期输出:
'example' // running and passing argument to context_manager
'works' // after yield executing some_func
【问题讨论】:
-
你能举例说明你想如何使用它吗?我不清楚你的班级应该做什么。
-
@Gerrat - 如果我定义了我的上下文管理器并尝试将其用作装饰器而不转换为装饰器,我会收到错误
object is not callable -
也许你可以展示你的示例函数(例如你的
some_func),以及你如何调用它以及你想要什么输出。真的不清楚你到底希望什么。 -
@Gerrat,不要听起来太混乱,而且我对装饰器和上下文管理器的理解很差,但我正在寻找一种方法来定义一个带参数的上下文管理器,我知道我可以通过
with声明,但如果可能,希望将其改为装饰器,保留传递参数的能力
标签: python decorator contextmanager