gpt4 book ai didi

python - isinstance(foo, types.GeneratorType) 还是 inspect.isgenerator(foo)?

转载 作者:太空狗 更新时间:2023-10-29 22:19:26 26 4
gpt4 key购买 nike

在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/

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