- Notifications
You must be signed in to change notification settings - Fork1k
Open
Description
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:
importasyncioimportsocketfromcollections.abcimportAsyncGenerator,Generator,Coroutine,Callabledefget_ipv4_by_hostname(hostname:str)->list[str]:returnlist(i[4][0]foriinsocket.getaddrinfo(hostname,0)ifi[0]issocket.AddressFamily.AF_INETandi[1]issocket.SocketKind.SOCK_RAW )asyncdefget_ipv4_by_hostname_async(hostname:str)->list[str]:returnawaitasyncio.to_thread(get_ipv4_by_hostname,hostname)asyncdefprint_domanin_ip(domain:str,get_ip:Callable[[str],Coroutine[None,None,list[str]]])->None:ips=awaitget_ip(domain)ifips:foripinips:print(f'{domain}:{ip}')else:print(f'{domain}: No IP found')print('_'*20)asyncdefmain()->None:awaitprint_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:
asyncdefecho_round()->AsyncGenerator[int,float]:sent=yield0whilesent>=0.0:rounded=awaitround(sent)sent=yieldrounded
I also guess that there might be a typo on the page 825, the image is provided below:
I think “to last” phrase should be removed becauseCoroutine
is actually covariant on the third parameter.
Metadata
Metadata
Assignees
Labels
No labels