この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
こんにちは。サービス部の武田です。
Python 3.5から型ヒントと呼ばれる機能が追加されました。Pythonは動的型付き言語ですが、変数の型をヒントとして宣言できる機能です。型ヒントは実際の挙動に影響は与えませんが、チェックツールを用いて静的に検査できます。
今回は小ネタとして特定の文字列(文字列リテラル)のみ受け入れる型を定義する方法を紹介します。次のようにtyping.Literal
で使用可能なリテラルを定義します。
main.py
from typing import Literal
Status = Literal["enabled", "disabled"]
def test(s: Status):
pass
test("enabled")
test("enable")
test("disabled")
test("off")
このスクリプトに対してmypy
でチェックしてみます。
$ mypy main.py
main.py:9: error: Argument 1 to "test" has incompatible type "Literal['enable']"; expected "Literal['enabled', 'disabled']"
main.py:11: error: Argument 1 to "test" has incompatible type "Literal['off']"; expected "Literal['enabled', 'disabled']"
Found 2 errors in 1 file (checked 1 source file)
enabled
とdisabled
の指定は問題ありませんが、その他の文字列はエラーになりました。
まとめ
typing.Literal
を使用することで特定の文字列のみ受け入れる型を定義できます。活用できそうな場面がありましたら、ぜひ使ってあげてください。