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

标签 python performance

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

相关文章:

python - Pandas:使用正则表达式替换列中的值

python - 正则表达式在 Rubular 中传递,但在 Python 中不传递

python - 将 CNN 从 tf.layers 重写为原始 tf 后性能不佳

mysql - 如何使我的 SELECT 查询更有效率?

python - django admin 在尝试更新记录时崩溃但在插入新记录时不崩溃

python - NearestNeighbors() 返回序列错误

c# - SQLite:.Net 比原生慢很多?

c++ - 求连接2N个点的线段的最小总长度

android - 动态改变Textview大小

php - 使用文本表代替 MySQL 表