型ヒント
配列
Nullable
1
2
3
4
5
6
7
8
9
10
11
12
13 | # Python 3.10以上
a: int | None
# Python 3.9以前
from typing import Optional
a: Optional[int] = 0
# こういう書き方もできるが、簡潔とは言えない
from typing import Union
a: Union[int, None] = 0
|
Lambda
| from typing import Callable
func: Callable[[int], bool] = lambda x: x >= 0
|
Any
| from typing import Any
a: Any = 0
|
自身
typing --- Support for type hints — Python 3.13.5 ドキュメント
Python 3.11 以降ではtyping.Selfで自身の型を示すことができる。
1
2
3
4
5
6
7
8
9
10
11
12 | from pathlib import Path
from typing import Self
class Page:
def __init__(self, filepath: str, content: str) -> None:
self.__filepath = filepath
self.__content = content
@classmethod
def from_file(cls, filepath: str) -> Self:
return Page(filepath, Path(filepath).read_text())
|