我想为一些将文件作为第一个参数的函数编写装饰器.装饰器必须实现context manager protocol(即将包装函数转换为上下文管理器),所以我想我需要用类包装函数.
我对装饰模式并不熟悉,之前从未实现过上下文管理器,但是我编写的内容在Python 2.7中工作,如果我注释掉换行符,它也适用于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
取消注释换行时出现的错误发生在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.有人可以解释一下这个回溯究竟是什么告诉我以及我该怎么做在两个版本的Python上实现包装效果?
编辑:我错了.上面的代码不符合我的要求.我希望能够使用和不使用的功能,如内置打开.
上面的代码将修饰函数转换为上下文管理器.我希望能够做到:
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
随意评论我忽略的任何事情.
注意:J.F.Sebastian的班级版似乎适用于:
我基本上从类中删除了包裹并将返回的CManager更改为:
@wraps(func)
def helper(*args, **kwargs):
return CManager(*args, **kwargs)
return helper
解决方法:
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
为了使它的行为完全相同,无论是直接使用装饰函数还是作为上下文管理器,你应该在__enter __()中返回self:
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()