PEP484について軽く説明
PEP 3107 FunctionAnnotations ってのがPythonに入ってPythonの関
数に、任意のメタデータを追加するための構文を導入する
def compile(source: "something compilable",
filename: "where the compilable thing comes from",
mode: "is this a single statement or a suite?"):
PEP3107 では特に意味づけがなかったものを Type Hint として使おうっ
ていうのがPEP484です
def greeting(name: str) -> str:
return 'Hello ' + name
NamedTuple
Point = namedtuple('Point',['x', 'y'])
p = Point(x=1, y=2)
print(p.z) # Error: Point has no attribute 'z'
Python 3.6 で以下のようにかけるようになった
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
PEP 526が入ったことでこういうのもProtocolっぽく動くよねっていう議論が
class Point(<somemagical base class):
x: float
y: float
z: float = 0
class MyPoint: # unrelated to Point
def __init__(self, x: float, y: float):
self.x, self.y = x, y
p = MyPoint(1, 2)
とこんな感じでまだ固まってないので typing.Protocol が使えるのはまだ先
のようです。
(typingの内部では使われているので興味ある方は読んでみるとよいかと)