Python “装饰师的作用是什么?”;实现“迭代器”?
Werkzeug v0.11 我研究了Werkzeug的源代码,文件wsgi.py中的ClosingIterator类,由函数decorted实现\u迭代器: wsgi.pyPython “装饰师的作用是什么?”;实现“迭代器”?,python,decorator,werkzeug,Python,Decorator,Werkzeug,Werkzeug v0.11 我研究了Werkzeug的源代码,文件wsgi.py中的ClosingIterator类,由函数decorted实现\u迭代器: wsgi.py @implements_iterator class ClosingIterator(object): """The WSGI specification requires that all middlewares and gateways respect the `close` callback of
@implements_iterator
class ClosingIterator(object):
"""The WSGI specification requires that all middlewares and gateways
respect the `close` callback of an iterator. Because it is useful to add
another close action to a returned iterator and adding a custom iterator
is a boring task this class can be used for that::
return ClosingIterator(app(environ, start_response), [cleanup_session,
cleanup_locals])
If there is just one close function it can be passed instead of the list.
A closing iterator is not needed if the application uses response objects
and finishes the processing if the response is started::
try:
return response(environ, start_response)
finally:
cleanup_session()
cleanup_locals()
"""
我在文件_compat.py中找到了实现_迭代器的定义:
implements_iterator = _identity
_identity = lambda x: x
问题是:
实现迭代器的功能是什么?Werkzeug同时针对Python2和Python3。如果在
compat.py
中向上滚动,您可以看到为Python 2定义了implements\u迭代器
,如下所示:
def implements_iterator(cls):
cls.next = cls.__next__
del cls.__next__
return cls
这允许一个类实现一个方法(仅在Python2中调用),并在不做任何修改的情况下同时适用于Python2和Python3