在Python中充当装饰器和上下文管理器的函数吗? [英] Function acting as both decorator and context manager in Python?

查看:106
本文介绍了在Python中充当装饰器和上下文管理器的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能会使事情有点过头,但主要出于好奇。

This might be pushing things a little too far, but mostly out of curiosity..

是否有可能有一个可调用的对象(函数/类) 同时充当上下文管理器和装饰器:

Would it be possible to have a callable object (function/class) that acts as both a Context Manager and a decorator at the same time:

def xxx(*args, **kw):
    # or as a class

@xxx(foo, bar)
def im_decorated(a, b):
    print('do the stuff')

with xxx(foo, bar):
    print('do the stuff')


推荐答案

从Python 3.2开始,标准库甚至都包含对此的支持。从类 contextlib.ContextDecorator 使编写可用作装饰器或上下文管理器的类变得容易。此功能可以很容易地反向移植到Python 2.x-这是一个基本的实现:

Starting in Python 3.2, support for this is even included in the standard library. Deriving from the class contextlib.ContextDecorator makes it easy to write classes that can be used as both, a decorator or a context manager. This functionality could be easily backported to Python 2.x -- here is a basic implementation:

class ContextDecorator(object):
    def __call__(self, f):
        @functools.wraps(f)
        def decorated(*args, **kwds):
            with self:
                return f(*args, **kwds)
        return decorated

从此类中派生上下文管理器并照常定义 __ enter __() __ exit __()方法。

Derive your context manager from this class and define the __enter__() and __exit__() methods as usual.

这篇关于在Python中充当装饰器和上下文管理器的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆