isinstance(foo,types.GeneratorType)或inspect.isgenerator(foo)?

Hor*_*Fat 6 python performance

似乎Python中有两种方法来测试对象是否是生成器:

import types
isinstance(foo, types.GeneratorType)
Run Code Online (Sandbox Code Playgroud)

要么:

import inspect
inspect.isgenerator(foo)
Run Code Online (Sandbox Code Playgroud)

本着"应该有一个 - 最好只有一个 - 显然是这样做的方式"的精神,是推荐的另一种方式之一(大概是他们做同样的事情......如果没有,请赐教我!)?

Bak*_*riu 7

它们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)
Run Code Online (Sandbox Code Playgroud)

我会说使用isinstance(object, types.GeneratorType)应该是首选方式,因为它更清晰,更简单.也inspect.isgenerator只是在python2.6中添加,这意味着使用isinstance更向后兼容.

他们可能添加了isgenerator对称功能,isgeneratorfunction它可以做出不同的事情.

  • +1用于警告我`inspect`模块中的`getsource`函数.这很酷! (2认同)