型ヒント
いろいろ
| # 配列
a: list[str] = []
# Noneあり
a: int | None # Python 3.10以上
a: Optional[int] = 0 # Python 3.9以前
a: Union[int, None] = 0
# lambda
from typing import Callable
func: Callable[[int], bool] = lambda x: x >= 0
|
自身を返す
Python 3.11 以降ではtyping.Self
で自身の型を示すことができる。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 | import re
from pathlib import Path
from typing import Self
class Page:
def __init__(self, filepath: str, content: str) -> None:
self.__filepath = filepath
self.__content = content
@property
def filepath(self) -> str:
return self.__filepath
@property
def content(self) -> str:
return self.__content
@property
def title(self) -> str | None:
result = re.findall(r'# (.+)', self.__content)
return result[0] if len(result) >= 1 else None
@property
def tags(self) -> list[str]:
return []
@classmethod
def from_file(filepath: str) -> Self:
return Page(filepath, Path(filepath).read_text())
|
Python 3.11 の新機能(その 6) 型ヒントの新機能 - PEP-673 Self 型: Python3.11 の新機能 - python.jp