アノテーション
Python3.5 で追加された機能のひとつにタイプヒントを利用した関数アノテーションがあります。(PEP-484-Type Hint)
また、Python3.6 から変数アノテーションができるようになりました。
(PEP-526-Syntax for Variable Annotations)
これにより、引数のあとにコロン(:)に続けて、その引数の説明やタイプヒントを記述できるようになりました。
code: 0111_function_annotation.py
def greeting(name: "Discription for Name"):
print(f'Hello {name}!')
greeting('Python')
デフォルト引数はアノテーションのあとに記述します。
code: 0112_function_annotation_with_default.py
def greeting(name: "Discription for Name"='Python'):
print(f'Hello {name}!')
greeting()
戻り値のアノテーションは引数定義の後に-> に続けて記述します。
code: 0113_function_annotation_with_return.py
def greeting(name: "Discription for Name"='Python') -> 'Greeting message':
return f'Hello {name}!'
print(greeting())
リスト型などの場合は次のように記述します。
code: 0114_function_annotation_return_list.py
from typing import List
def greeting(names: Liststr) -> None:
for student in names:
print(student)
greeting('Freddie', 'David')
変数が多いようなときは、次のように複数行で関数を定義することもできます。
code: 0115_function_annotation_many_args.py
def headline(
text: str,
width: int=80,
fill_char: str="-",
): -> str
return f" {text.title()} ".center(width, fill_char)
print(headline("type comments work", width=40))
アノテーションは単純にコメントとして無視されます。タイプヒントとして型やオブジェクトIDを書くこともできますが、型チェックや呼び出しが行われるわけではありません。
code: 0116_function_annotation_not_validate.py
def greeting(name: str) -> str:
return f'Hello {name}!'
print(greeting(1))
アノテーションは__annotations__アトリビュートに格納されています。
code: 0117_function_annotation_attributes.py
def greeting(name: "Discripion for Name"='Python') -> 'Greeting message':
return f'Hello {name}!'
print(greeting.__annotations__)
code: bash
$ python 0117_function_annotation_attributes.py
{'name': 'Discripion for Name', 'return': 'Greeting message'}
引数の値によって、複数の型を返すような関数では、次のように記述します。
code: 0118_function_annotation_union.py
from typing import Union
def add(first_value: int, second_value: int) -> Unionint, bool:
if first_value == 0:
return False
return first_value + second_value
print(add(1,10))
補足
タイプヒントは、あくまでヒントであって実行時には何の役にも立ちませんが、mypy というツールを使って関数への型の受け渡しを静的にチェックすることができます。
次のようなケースでは、タイプヒントを定義しておくことはコードの品質に大きく寄与するものになります。
プログラムの規模が大きくなっていく。
担当する開発者が増えていく。
コードの手離れを良くしたい。
修正頻度が高い。
また、Python の IDE である PyCharm や Visual Studio などでも PEP 484 に対応していて、
誤った呼び出しかたをすると警告を出してくれるようになっています。
参考:
Python公式ドキュメント 関数定義
Python 公式ドキュメント typing - support for type hint
PEP 3107 -- Function Annotations
PEP 484 – Type Hints
previous: 関数をネストする
next: f-stringの詳細
#Pythonセミナー上級編