即使我没有在功能中点击yield关键字,为什么我仍然会收到生成器

时间:2018-05-25 13:07:25

标签: python database python-3.x postgresql psycopg2

$tagList = explode(",", $tags);

// Loop through the tag array that we just created
foreach ($tagList as $tags) {
    $tag = Tag::firstOrCreate(['slug' => $tags];
}

$tags = Tag::whereIn('name', $tagList)->get()->pluck('id')->get();
$article->tags()->sync($tags);

在上面的函数中,数据类型应该是一个列表作为参数batchsize = None。 但这个功能在两种情况下都返回发电机。 如果我评论该函数的其他部分,那么它将返回一个列表。

1 个答案:

答案 0 :(得分:3)

啊,我得到了你所要求的。你在问:

  

即使我未在yield点击get_data()关键字,为什么仍然会收到生成器?

问题是包含至少一个yield语句的函数是一个生成器。因此,您的get_data() 功能是一个生成器。因此,您总是会收到get_data()之外的生成器对象。

生成器中return的含义与普通函数略有不同。在生成器中,任何return x语句都等同于raise StopIteration(x)

当您使用else注释掉部分时,您会注释掉yield语句,因此get_data()成为普通函数。因此,它会按预期返回list

相关SO帖子:Return and yield in the same function