19. 型アノテーションの基礎(1)–typing
a: str = "Hello, World!" # OK
b: int = "Hello, World!" # NG
c = "Hello, World!" # c は str と推論される
c = 3 # NG: c は str なのでエラー
d: str | int = "Hello, World!" # OK: Python 3.10 未満では Union[str, int]
d = 3 # OK
d = [3] # NG: list[int] を代入しようとしている
e: Any = "Hello, World!" # OK
e = 3 # OK
e = [3] # OK
22. 型アノテーションの基礎(4)–typing
a: Optional[int] = 1 # OK: Optional[int] は int | None と同じ意味
a = None # OK
a = "string" # NG: int でも None でもない
def _sq_opt(x: Optional[int]) -> int:
return x * x # NG: x は None かもしれない
def sq_opt(x: Optional[int]) -> int:
if x is None:
return 0
return x * x # OK: ここでは x が None ではない保証がある
def union_test(x: str | int) -> None:
y: int = x # NG: x は str かもしれない
if isinstance(x, int):
y: int = x # OK
else: # ここが isinstance(x, str) だと pyright が警告 (reportUnnecessaryIsInstance)
y: str = x # OK
36. 型検査の限界 (型検査の曖昧性)–typing
🤔
m: list[float] = [1.0, 2, True] # OK
[type(x) for x in m]
# [<class 'float'>, <class 'int'>, <class 'bool'>]
[x * x for x in m]
# [1.0, 4, 1]
[type(x * x) for x in m]
# [<class 'float'>, <class 'int'>, <class 'int'>]
41. 処理の継続(3)–async/await
await 構文を使うと同じようなことを見た目は同期的に書ける
asyncdef したものはクロージャ (正確にはコルーチン) になる
await するとコルーチンを実行した結果を受け取れる
async def A(x):
# A の処理
return result # A の結果を返す
async def B(x):
# B の処理
return result # B の結果を返す
async def C(x):
# C の処理
return result # C の結果を返す
a = await A(0)
b = await B(a)
c = await C(b)