Python 2.7 yield正在创建奇怪的行为

时间:2014-06-23 20:18:50

标签: python python-2.7

使用Python 2.7 ....

print thread["Subject"]应该返回:

please ignore - test2 

Please ignore - test

它确实成功了:

def thread_generator(threads):
    tz = pytz.timezone('America/Chicago')
    POSTS_SINCE_HOURS = 24
    now_date = datetime.datetime.now(tz)
    time_stamp = now_date - datetime.timedelta(hours=POSTS_SINCE_HOURS)
for thread in threads:
    last_post_time = convert_time(thread["LatestPostDate"])

    if last_post_time > time_stamp:
        print thread["Subject"]
        row = {
            "url": thread["Url"],
            "author_username": thread["Author"]["Username"],
            "author_name": thread["Author"]["DisplayName"],
            "thread_id": thread["Id"],
            "forum_id": thread["ForumId"],
            "subject": thread["Subject"],
            "created_date": thread["Content"]["CreatedDate"],
            "reply_count": thread["ReplyCount"],
            "latest_post_date": thread["LatestPostDate"],
            "latest_reply_author": thread["LatestForumReplyAuthorId"] }

但是,在添加yield row print thread["Subject"]时,Please ignore - test并未显示def thread_generator(threads): tz = pytz.timezone('America/Chicago') POSTS_SINCE_HOURS = 24 now_date = datetime.datetime.now(tz) time_stamp = now_date - datetime.timedelta(hours=POSTS_SINCE_HOURS) for thread in threads: last_post_time = convert_time(thread["LatestPostDate"]) if last_post_time > time_stamp: print thread["Subject"] row = { "url": thread["Url"], "author_username": thread["Author"]["Username"], "author_name": thread["Author"]["DisplayName"], "thread_id": thread["Id"], "forum_id": thread["ForumId"], "subject": thread["Subject"], "created_date": thread["Content"]["CreatedDate"], "reply_count": thread["ReplyCount"], "latest_post_date": thread["LatestPostDate"], "latest_reply_author": thread["LatestForumReplyAuthorId"] } yield row

Please ignore - test

这是为什么? print thread["Subject"]仍应显示def sanitize_threads(threads): for thread in thread_generator(threads): do stuff thread_batch.append(thread) return thread_batch def get_unanswered_threads(): slug = 'forums/threads/unanswered.json?PageSize=100' status_code, threads = do_request(slug) if status_code == 200: threads = threads["Threads"] thread_batch = sanitize_threads(threads) database_update(thread_batch) 。对我毫无意义。

更新:如何调用生成器

{{1}}

1 个答案:

答案 0 :(得分:3)

您是否尝试在生成的生成器上实际调用next()?如果您使用yield调用函数的方式与调用函数的方式相同,则在yield情况下,您将获得生成器对象。生成器不会评估其中的内容,直到您实际需要它的值,这可以使用next(generator)来完成。

例如:

>>> def nogen():
...   '''Create a list of values 0-3 and print each one as you build the list.'''
...   r = []
...   for i in range(3):
...     print(i)
...     r.append(i)
...   return r
... 
>>> def firstgen():
...   '''Create an iterator of values 0-3 and print each one as you yield the value.'''
...   for i in range(3):
...     print(i)
...     yield i
... 
>>> a = nogen() # This function is eager and does everything at once.
0
1
2
>>> a
[0, 1, 2]
>>> b = firstgen() # Note there's no output immediately after this line.
>>> list(b) # The output happens as the list coercion causes the generator to execute.
0
1
2
[0, 1, 2]
>>> c = firstgen() # You can also see this a step at a time using `next`
>>> next(c)
0
0
>>> next(c)
1
1
>>> next(c)
2
2
>>> next(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration