kb84tkhrのブログ

何を書こうか考え中です あ、あと組織とは関係ないってやつです 個人的なやつ

寄り道:Type Hint (続き)

少し遊ぶ
ヒントに合わない型を返してみるとか

>>> def greeting(name: str) -> int:
...     return 'Hello ' + name
...
>>>

あれ?

>>> greeting("Taro")
'Hello Taro'

あれれ?
こういうところをチェックするものじゃないのかな
じゃあこうしておいて

>>> def print_greeting(greet: str) -> None:
...     print(greet)
...

こうするとエラーになるのでは?

>>> print_greeting(greeting("Taro"))
Hello Taro
>>>

ならないね
なんぞ
もうちょっとちゃんと調べないとダメか
これでも読むか

PEP 484 -- Type Hints | Python.org

と思ったらかなり冒頭で答えが

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily.

実行時には型チェックしてないよ、別のツール使って自分でチェックしてね!

あらそうなの
さっきちょっとエラーにしてくれたじゃない

The proposal is strongly inspired by mypy.

この提案はmypyにとってもインスパイアされてるよ!

ではさっそく入れてみて

$ pip3 install mypy

type-hint.pyっていう名前のファイル作って

def greeting(name: str) -> int:
    return 'Hello ' + name

やってみる

$ mypy type-hint.py
type-hint.py:2: error: Incompatible return value type (got "str", expected "int")

おーぱちぱちぱち

最低限のことはできたのであとはざっと斜め読み
ジェネリックも書けるんだな
あとはやりながら必要になったら調べていこう

ところで
ダックタイピングはどうサポートされるんだろうと思ったけど
直接はサポートされてないように見えた
xはこんなメソッドを持つクラスである、っていうようなヒントが
書けたりするのかなーと思ったけど

型ヒントつけたいから継承するってのも変だし
でもAnyしか使えないっていうのもうれしくないね?
どうするのかな