装饰器 "implements_iterator" 的作用是什么?

What is the function of the decorator "implements_iterator" ?

Werkzeug v0.11 我研究了 Werkzeug 的源代码,文件 wsgi.py 中的 class ClosingIterator,由函数 implements_iterator:

装饰

wsgi.py

@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 的定义:

implements_iterator = _identity

_identity = lambda x: x

问题是: implements_iterator 的功能是什么?

Werkzeug 同时针对 Python 2 和 Python 3。如果您在 compat.py 中向上滚动,您可以看到 implements_iterator 是为 Python 定义的2如下:

def implements_iterator(cls):
    cls.next = cls.__next__
    del cls.__next__
    return cls

这允许 class 在 Python 2) 中实现 __next__ method (called just next 并且无需任何修改即可用于 Python 2 和 3。