问题描述
我有一个修饰函数,我想同时应用于普通函数和生成器。当应用于正常功能时,它可以正常工作。但是,当将其应用于生成器时,装饰器内部的迭代循环将执行到最后,但此后脚本将引发错误:
I have a decorator function which I want to apply to both normal function and a generator. When applied to the normal function, it works properly. However, when applied to the generator, the iteration loop inside the decorator is executed till the end, but after that the script throws an error:
TypeError: 'NoneType' object is not iterable
并退出脚本。
def decor(func):
def wrapper(*args, **kwargs):
func_name = func.__name__
is_generator = "_generator" in func_name
if is_generator:
for item in func(*args, **kwargs):
print(item)
else:
res = func(*args, **kwargs)
print(res)
return wrapper
@decor
def f():
return "a"
@decor
def f_generator():
for i in range(2):
yield "b"
f()
""" Output: a """
for item in f_generator():
print ("Processing item ", item)
"""
Output:
b
b
Traceback (most recent call last):
File "test.py", line 27, in <module>
for item in f_generator():
TypeError: 'NoneType' object is not iterable
"""
此外,将装饰器应用于生成器时,外部生成器调用的 print(正在处理项目,项目)
为
从生成器中删除装饰器后,就可以调用生成器并且它可以正常运行。
Furthermore, when the decorator is applied to the generator, the print ("Processing item ", item)
of the external generator call is not executed.Once I remove the decorator from the generator, I can call the generator and it functions properly.
如何解决该问题,以便我可以将装饰器应用到生成器并使其正常工作吗?
尝试通过异常处理错误可以消除错误,并且脚本将完全执行,但是随后 print(处理项目,项目)
仍未执行。
How do I fix the problem so that I can apply the decorator to the generator and get it working without an error?Trying to handle the error with an exception takes away the error and the script is executed entirely, but then the print ("Processing item ", item)
is still not being executed.
推荐答案
添加 @decorator
,中的
实际上是 f_generator()
用于f_generator()中的项目: decor(f_generator)
。由于 decor()
不会产生或返回任何东西,所以它是不可迭代的自己,您应该为func(* args,** kwargs)中的项目在附近添加
收益项目
:
When you add @decorator
, f_generator()
in for item in f_generator():
is actually decor(f_generator)
. Since decor()
does not yield or return anything, it's not iterable itself, you should add yield item
around for item in func(*args, **kwargs):
这篇关于TypeError:将装饰器应用于生成器时,“ NoneType”对象不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!