在Python中似乎有两种方法来测试一个对象是否是生成器:
import types
isinstance(foo, types.GeneratorType)
或:
import inspect
inspect.isgenerator(foo)
本着“应该有一种 - 最好只有一种 - 显而易见的方法”的精神,推荐这些方法中的一种而不是另一种(大概他们做同样的事情......如果不是,请赐教!)?
最佳答案
它们是 100% 等效的:
>>> print(inspect.getsource(inspect.isgenerator))
def isgenerator(object):
"""Return true if the object is a generator.
Generator objects provide these attributes:
__iter__ defined to support interation over container
close raises a new GeneratorExit exception inside the
generator to terminate the iteration
gi_code code object
gi_frame frame object or possibly None once the generator has
been exhausted
gi_running set to 1 when generator is executing, 0 otherwise
next return the next item from the container
send resumes the generator and "sends" a value that becomes
the result of the current yield-expression
throw used to raise an exception inside the generator"""
return isinstance(object, types.GeneratorType)
我会说使用 isinstance(object, types.GeneratorType)
应该是首选方式,因为它更清晰、更简单。
另外inspect.isgenerator
是python2.6才加入的,这意味着使用isinstance
更加向后兼容。
他们可能为对称添加了isgenerator
函数isgeneratorfunction
它做了一些不同的事情。
关于python - isinstance(foo, types.GeneratorType) 还是 inspect.isgenerator(foo)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19500030/