fluentpython/example-code-2e

Suggestion: Add more examples for “Type Hinting Asynchronous Objects” section in chapter 21

kamalfarahani opened this issue · 0 comments

Dear Ramalho,

I hope you are well. I'm writing to suggest an improvement for the “Type Hinting Asynchronous Objects” section in Chapter 21 for the next edition.

Enhancing Clarity with Examples

I believe that including additional examples in this section would significantly enhance understanding of how to properly use type hints for asynchronous objects. Here are some specific suggestions:

  • Coroutines Example: A beneficial addition would be an example demonstrating type hints for coroutines. The following code showcases how to achieve this:
import asyncio
import socket

from collections.abc import AsyncGenerator, Generator, Coroutine, Callable


def get_ipv4_by_hostname(hostname: str) -> list[str]:
    return list(
        i[4][0]
        for i in 
        socket.getaddrinfo(hostname, 0)
        if i[0] is socket.AddressFamily.AF_INET
        and i[1] is socket.SocketKind.SOCK_RAW  
    )


async def get_ipv4_by_hostname_async(hostname: str) -> list[str]:
    return await asyncio.to_thread(get_ipv4_by_hostname, hostname)


async def print_domanin_ip(
        domain: str,
        get_ip: Callable[[str], Coroutine[None, None, list[str]]]) -> None:
    ips = await get_ip(domain)
    if ips:
        for ip in ips:
            print(f'{domain}: {ip}')
    else:
        print(f'{domain}: No IP found')
    print('_' * 20)


async def main() -> None:
    await print_domanin_ip('docker.com', get_ipv4_by_hostname_async)
  • AsyncGenerators Example: The official typing documentation provides an excellent and clear example for AsyncGenerators. Including a similar example in the book would be valuable:
async def echo_round() -> AsyncGenerator[int, float]:
    sent = yield 0
    while sent >= 0.0:
        rounded = await round(sent)
        sent = yield rounded

I also guess that there might be a typo on the page 825, the image is provided below:
typo

I think “to last” phrase should be removed because Coroutine is actually covariant on the third parameter.