2017-10-09  3,973
 

Author: lightless@Meili-inc

Date: 20171009

0x00 前言

0x01 起:一切从生成器开始

def my_range(max_number):
    sequence = []
    index = 0
    while index < max_number:
        sequence.append(index)
        index += 1
    return sequence

def lazy_range(max_number):
    index = 0
    while index < max_number:
        yield index
        index += 1

当函数执行遇到yield的时候,会暂停执行。这样只需在内存中维护可以存储一个整数的内存空间就可以了。如果对生成器/迭代器不理解的话,可以参考Stack Overflow上的这篇高票回答:传送门

0x02 承:协程诞生

def smart_range(max_number):
    index = 0
    while index < max_number:
        jump = yield index
        if jump is None:
            jump = 1
        index += jump

def lazy_range(max_number):
    index = 0
    
    def gratuitous_refactor():
        while index < max_number:
            yield index
            index += 1
    yield from gratuitous_refactor()

import asyncio

@asyncio.coroutine
def counttdown(number, n):
    while n > 0:
        print("T-minus", n, "({})".format(number))
        yield from asyncio.sleep(1)
        n -= 1

loop = asyncio.get_event_loop()
tasks = [
    asyncio.ensure_future(counttdown("A", 2)),
    asyncio.ensure_future(counttdown("B", 5)),
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

[转载] Python协程从零开始到放弃

0x03 转:从yield from到await

# python34
@asyncio.coroutine
def py34_function():
    yield from work()

# python35
async def py35_function():
    await work()

result = [i async for i in aiter() if i % 2]
result = [await func() for fun in funcs if await condition()]

async def test(x, y):
    for i in range(y):
        yield i
        await asyncio.sleep(x)

0x04 合:尾声

How the heck does async/await work in Python 3.5?

Python协程:从yield/send到async/await

Python黑魔法 --- 异步IO( asyncio) 协程

Keynote at PyCon Brasil 2015 (Screencast)

 
转自 https://www.secpulse.com/archives/61398.html

相关文章:

  • 2021-09-19
  • 2021-10-06
  • 2021-03-28
  • 2021-12-24
猜你喜欢
  • 2021-12-06
  • 2021-10-06
  • 2021-11-25
  • 2021-04-21
  • 2022-01-13
  • 2022-01-29
  • 2021-06-23
相关资源
相似解决方案