装饰器“implements_iterator”的功能是什么?

时间:2017-09-23 06:36:32

标签: python decorator werkzeug

Werkzeug v0.11 我试着Werkzeug的源代码,文件wsgi.py中的类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的功能是什么?

1 个答案:

答案 0 :(得分:3)

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

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

这允许类实现__next__方法(在Python 2中称为next),并且无需任何修改即可为Python 2和3工作。