fluentpython / example-code-2e

Example code for Fluent Python, 2nd edition (O'Reilly 2022)
https://amzn.to/3J48u2J
MIT License
3.26k stars 919 forks source link

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

Open kamalfarahani opened 5 months ago

kamalfarahani commented 5 months ago

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:

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)

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.