Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kamalfarahani opened this issue May 5, 2024 · 0 comments

Comments

@kamalfarahani
Copy link

kamalfarahani commented May 5, 2024

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.

@kamalfarahani kamalfarahani changed the title Suggestion: Add more examples for “Type Hinting Asynchronous Objects” section of chapter 21 Suggestion: Add more examples for “Type Hinting Asynchronous Objects” section in chapter 21 May 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant