7

我想为一些将文件作为第一个参数的函数编写一个装饰器。装饰器必须实现上下文管理器协议(即将包装的函数变成上下文管理器),所以我想我需要用一个类来包装函数。

我对装饰器模式并没有真正的经验,并且以前从未实现过上下文管理器,但是我编写的内容适用于 Python 2.7,如果我注释掉该wraps行,它也适用于 Python 3.3。

from functools import wraps
def _file_reader(func):
    """A decorator implementing the context manager protocol for functions
    that read files."""
#   @wraps(func)
    class CManager:
        def __init__(self, source, *args, **kwargs):
            self.source = source
            self.args = args
            self.kwargs = kwargs
            self.close = kwargs.get('close', True)

        def __enter__(self):
            # _file_obj is a little helper that opens the file for reading
            self.fsource = _file_obj(self.source, 'r') 
            return func(self.fsource, *self.args, **self.kwargs)

        def __exit__(self, exc_type, exc_value, traceback):
            if self.close:
                self.fsource.close()
            return False
    return CManager

取消注释该wraps行时出现的错误发生在内部update_wrapper

/usr/lib/python3.3/functools.py in update_wrapper(wrapper, wrapped, assigned, updated)
     54             setattr(wrapper, attr, value)
     55     for attr in updated:
---> 56         getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
     57     # Return the wrapper so this can be used as a decorator via partial()
     58     return wrapper

AttributeError: 'mappingproxy' object has no attribute 'update'

我知道文档并没有说我什至可以用functools.wraps这样的类来包装函数,但话又说回来,它只适用于 Python 2。有人可以解释一下这个回溯到底告诉我什么以及我应该做什么wraps在两个版本的Python上实现效果?


编辑:我错了。上面的代码没有做我想要的。我希望能够在没有 with的情况下使用该函数,例如内置函数open

上面的代码将修饰函数转换为上下文管理器。我希望能够做到:

reader = func('source.txt', arg)
for item in reader:
    pass

with func('source.txt', arg) as reader:
    for item in reader:
        pass

所以我的代码版本应该大概如下所示:

def _file_reader(func):
    """A decorator implementing the context manager protocol for functions
    that read files."""
    @wraps(func)
    class CManager:
        def __init__(self, source, *args, **kwargs):
            self.close = kwargs.get('close', True)
            self.fsource = _file_obj(source, 'r')
            self.reader = func(self.fsource, *args, **kwargs)

        def __enter__(self):
            return self.reader

        def __iter__(self):
            return self.reader

        def __next__(self):
            return next(self.reader)

        def __exit__(self, exc_type, exc_value, traceback):
            if self.close and not self.fsource.closed:
                self.fsource.close()
            return False
    return CManager

随意评论我忽略的任何事情。

注意:JF Sebastian 的课程版本似乎可以工作:

我基本上wraps从课堂上删除了并改为return CManager

@wraps(func)
def helper(*args, **kwargs):
    return CManager(*args, **kwargs)
return helper
4

2 回答 2

3

functools.wraps()用于包装函数:

import contextlib
import functools

def file_reader(func):
    @functools.wraps(func)
    @contextlib.contextmanager
    def wrapper(file, *args, **kwargs):
        close = kwargs.pop('close', True) # remove `close` argument if present
        f = open(file)
        try:
            yield func(f, *args, **kwargs)
        finally:
            if close:
               f.close()
    return wrapper

例子

@file_reader
def f(file):
    print(repr(file.read(10)))
    return file

with f('prog.py') as file:
    print(repr(file.read(10)))

如果您想使用基于类的上下文管理器,那么解决方法是:

def file_reader(func):
    @functools.wraps(func)
    def helper(*args, **kwds):
        return File(func, *args, **kwds)
    return helper

为了使其行为相同,无论装饰函数是直接使用还是作为上下文管理器,您应该self返回__enter__()

import sys

class File(object):

    def __init__(self, file, func, *args, **kwargs):
        self.close_file = kwargs.pop('close', True)
        # accept either filename or file-like object
        self.file = file if hasattr(file, 'read') else open(file)

        try:
            # func is responsible for self.file if it doesn't return it
            self.file = func(self.file, *args, **kwargs)
        except:  # clean up on any error
            self.__exit__(*sys.exc_info())
            raise

    # context manager support
    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        if not self.close_file:
            return  # do nothing
        # clean up
        exit = getattr(self.file, '__exit__', None)
        if exit is not None:
            return exit(*args, **kwargs)
        else:
            exit = getattr(self.file, 'close', None)
            if exit is not None:
                exit()

    # iterator support
    def __iter__(self):
        return self

    def __next__(self):
        return next(self.file)

    next = __next__  # Python 2 support

    # delegate everything else to file object
    def __getattr__(self, attr):
        return getattr(self.file, attr)

例子

file = f('prog.py')  # use as ordinary function
print(repr(file.read(20)))
file.seek(0)
for line in file:
    print(repr(line))
    break
file.close()
于 2012-12-30T23:00:01.373 回答
2

虽然我不知道看到的错误是什么,但看起来你可能注定要失败:

>>> import functools
>>> def foo():
...     pass
... 
>>> class bar:
...     pass
... 
>>> functools.wraps(foo)(bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.2/functools.py", line 48, in update_wrapper
    setattr(wrapper, attr, value)
AttributeError: attribute '__doc__' of 'type' objects is not writable
>>> bar.__doc__
>>> bar.__doc__ = 'Yay'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: attribute '__doc__' of 'type' objects is not writable

编辑: JF Sebastian解决方案,但我将这一点作为说明为什么它必须是一个函数而不是一个类

于 2012-12-30T22:43:19.240 回答