complete draft: update from Atlas

This commit is contained in:
Luciano Ramalho
2021-06-09 00:13:02 -03:00
parent 08a4001b43
commit 135eca25d9
43 changed files with 4705 additions and 3240 deletions

View File

@@ -0,0 +1,2 @@
# Mypy 0.812 can't spot this inevitable runtime IndexError
print([][0])

View File

@@ -0,0 +1,23 @@
# tag::CAST[]
from typing import cast
def find_first_str(a: list[object]) -> str:
index = next(i for i, x in enumerate(a) if isinstance(x, str))
# We only get here if there's at least one string in a
return cast(str, a[index])
# end::CAST[]
from typing import TYPE_CHECKING
l1 = [10, 20, 'thirty', 40]
if TYPE_CHECKING:
reveal_type(l1)
print(find_first_str(l1))
l2 = [0, ()]
try:
find_first_str(l2)
except StopIteration as e:
print(repr(e))

View File

@@ -0,0 +1,37 @@
import asyncio
from asyncio import StreamReader, StreamWriter
# tag::CAST_IMPORTS[]
from asyncio.trsock import TransportSocket
from typing import cast
# end::CAST_IMPORTS[]
async def handle_echo(reader: StreamReader, writer: StreamWriter) -> None:
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
print("Close the connection")
writer.close()
async def main() -> None:
server = await asyncio.start_server(
handle_echo, '127.0.0.1', 8888)
# tag::CAST_USE[]
socket_list = cast(tuple[TransportSocket, ...], server.sockets)
addr = socket_list[0].getsockname()
# end::CAST_USE[]
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main())

View File

@@ -0,0 +1,29 @@
import asyncio
from asyncio import StreamReader, StreamWriter
async def handle_echo(reader: StreamReader, writer: StreamWriter) -> None:
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
print("Close the connection")
writer.close()
async def main() -> None:
server = await asyncio.start_server(
handle_echo, '127.0.0.1', 8888)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main())