|
| 1 | +#!/usr/bin/env python3.11 |
| 2 | + |
| 3 | +# https://docs.python.org/3.11/whatsnew/3.11.html |
| 4 | + |
| 5 | +from passed import passed |
| 6 | + |
| 7 | +import asyncio |
| 8 | +import enum |
| 9 | +import tomllib |
| 10 | + |
| 11 | + |
| 12 | +# ExceptionGroup and except* (PEP 654) |
| 13 | +def _raise_exception_group() -> None: |
| 14 | + raise ExceptionGroup( |
| 15 | + "demo", |
| 16 | + [ValueError("bad value"), TypeError("bad type")], |
| 17 | + ) |
| 18 | + |
| 19 | + |
| 20 | +handled_value_error = False |
| 21 | +handled_type_error = False |
| 22 | + |
| 23 | +try: |
| 24 | + _raise_exception_group() |
| 25 | +except* ValueError as eg: |
| 26 | + handled_value_error = True |
| 27 | + # Each subgroup only contains the matched exception type |
| 28 | + assert all(isinstance(e, ValueError) for e in eg.exceptions) |
| 29 | +except* TypeError as eg: |
| 30 | + handled_type_error = True |
| 31 | + assert all(isinstance(e, TypeError) for e in eg.exceptions) |
| 32 | + |
| 33 | +assert handled_value_error and handled_type_error |
| 34 | + |
| 35 | + |
| 36 | +# tomllib in the standard library (PEP 680) |
| 37 | +toml_text = """ |
| 38 | +name = "alice" |
| 39 | +age = 42 |
| 40 | +""" |
| 41 | +data = tomllib.loads(toml_text) |
| 42 | +assert data == {"name": "alice", "age": 42} |
| 43 | + |
| 44 | +# enum.StrEnum (bakes in str behavior) |
| 45 | +class Color(enum.StrEnum): |
| 46 | + RED = "red" |
| 47 | + BLUE = "blue" |
| 48 | + |
| 49 | +assert Color.RED == "red" |
| 50 | +assert isinstance(Color.BLUE, str) |
| 51 | + |
| 52 | +# asyncio.TaskGroup (structured concurrency) |
| 53 | +async def _tg_demo() -> int: |
| 54 | + async with asyncio.TaskGroup() as tg: |
| 55 | + task_one = tg.create_task(asyncio.sleep(0.01, result=1)) |
| 56 | + task_two = tg.create_task(asyncio.sleep(0.01, result=2)) |
| 57 | + return task_one.result() + task_two.result() |
| 58 | + |
| 59 | +assert asyncio.run(_tg_demo()) == 3 |
| 60 | + |
| 61 | +passed() |
0 commit comments