本文介绍了isinstance(foo, types.GeneratorType) 或 inspect.isgenerator(foo)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中似乎有两种方法可以测试一个对象是否是生成器:

导入类型isinstance(foo, types.GeneratorType)

或:

导入检查检查.isgenerator(foo)

本着应该有一种——最好只有一种——明显的方法来做到这一点."的精神,是推荐的这些方法之一(大概它们做同样的事情......如果不是,请赐教!)?

解决方案

它们 100% 等效:

>>>打印(inspect.getsource(inspect.isgenerator))def isgenerator(object):"""如果对象是生成器,则返回 true.生成器对象提供以下属性:__iter__ 定义为支持容器交互close 在内部引发了一个新的 GeneratorExit 异常生成器终止迭代gi_code 代码对象gi_frame 框架对象或可能 None 一旦生成器具有已经筋疲力尽gi_running 在生成器执行时设置为 1,否则为 0next 从容器中返回下一个项目send 恢复生成器并发送"一个值,该值变为当前产量表达式的结果throw 用于在生成器内部引发异常"""返回 isinstance(object, types.GeneratorType)

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

他们可能为对称添加了 isgenerator 函数 isgeneratorfunction 做了一些不同的事情.

It seems that there are two ways in Python to test whether an object is a generator:

import types
isinstance(foo, types.GeneratorType)

or:

import inspect
inspect.isgenerator(foo)

In the spirit of "There should be one-- and preferably only one --obvious way to do it.", is one of these ways recommended over the other (presumably they do the same thing...if not, please enlighten me!)?

解决方案

They are 100% equivalent:

>>> 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)

I'd say that using isinstance(object, types.GeneratorType) should be the preferred way since it's clearer and simpler.Also inspect.isgenerator was only added in python2.6, which means that using isinstance is more backward compatible.

They probably added the isgenerator function for symmetry isgeneratorfunction which does something different.

这篇关于isinstance(foo, types.GeneratorType) 或 inspect.isgenerator(foo)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 22:50