gpt4 book ai didi

python - 装饰器 "implements_iterator"的功能是什么?

转载 作者:行者123 更新时间:2023-11-30 22:29:26 27 4
gpt4 key购买 nike

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 的作用是什么?

最佳答案

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

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

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

关于python - 装饰器 "implements_iterator"的功能是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376804/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com