Python Zero to Heros

Online Absolute Beginner Python TutorialsΒ 

Every Sunday 2pm (UK time/ BST)

Get this slide deck:

slides.com/cheukting_ho/python-async

Recap

Beginner topics:

Python objects - int, float, str, list, dict, bool

Control flows - if-else, for loop, while loop

Functions, modeuls, classes and decorators

strings operations and regex with re

Testing:

pytest with fixtures and mock

property-based testing

python linters & auto-formatters

TDD

Intermedite topics:

Iterators, generators

Let's continue our story...

πŸ“–
Once upon a time there are Generators

Sending to generator

Β 

The send() method resumes the generator and sends a value that will be used to continue with the next yield. The method returns the new value yielded by the generator.

- https://stackabuse.com/python-generators/

def numberGenerator(n):
     number = yield
     while number < n:
         number = yield number 
         number += 1

g = numberGenerator(10)    # Create our generator
next(g)                    # 
print(g.send(5))

Python 3.3 : yield from

def generator1():
    for item in generator2():
        yield item
def generator1():
    yield from generator2()

Python 3.3+ : yield from

def bottom():
    # Returning the yield lets the value
    # that goes up the call stack
    # to come right back down.
    return (yield 42)

def middle():
    return (yield from bottom())

def top():
    return (yield from middle())

# Get the generator.
gen = top()
value = next(gen)
print(value)  # Prints '42'.
try:
    value = gen.send(value * 2)
except StopIteration as exc:
    value = exc.value
print(value)  # Prints '84'.

Event Loop πŸ™†πŸ»β€β™€οΈ

and

Coroutine πŸ™‹πŸ»β€β™€οΈ

Event Loop πŸ™†πŸ»β€β™€οΈ

Β 

An event loopΒ is a loop that can register tasks to be executed, execute them, delay or even cancel them and handle different events related to these operations.

Β 

Β 

...like a

Task manager πŸ‘©πŸ»β€πŸ’Ό

Coroutine πŸ™‹πŸ»β€β™€οΈ

Β 

CoroutinesΒ are computer program components that generalize subroutines for nonpreemptive multitasking, by allowing multiple entry points for suspending and resuming execution at certain locations

- wikipedia

Β 

...like a

YouTube video 🎬

Python 3.4: asyncio

import asyncio

# Borrowed from http://curio.readthedocs.org/en/latest/tutorial.html.
@asyncio.coroutine
def countdown(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(countdown("A", 2)),
    asyncio.ensure_future(countdown("B", 3))]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

Python 3.5: asyn await

async def py35_coro():
    await stuff()

Python 3.4: asyncio

@asyncio.coroutine
def py34_coro():
    yield from stuff()

Can we rewrite our code with async await?Β 

Β 

πŸ€”

Big thanks to
Brett Cannon

πŸ‘πŸ»πŸ‘πŸ»πŸ‘πŸ»πŸ‘πŸ»πŸ‘πŸ»πŸ‘πŸ»πŸ‘πŸ»

Please read his blog post:

https://snarky.ca/how-the-heck-does-async-await-work-in-python-3-5/

Next week:
docstring magics

Sunday 2pm (UK time/ BST)

There are also Mid Meet Py every Wednesday 1pm

Python Async

By Cheuk Ting Ho

Python Async

  • 279
Loading comments...

More from Cheuk Ting Ho