mypyのLiteral typesのお供には--strict-equalityオプションを

Type hints

pythonでも型を書きたいですよね。type hintsがあります。

これが

def hello(name):
    return f"hello {name}!"

こう。

def hello(name: str) -> str:
    return f"hello {name}!"

型が指定できます。

Literal types

ところで型の指定は文字列型だけで十分ですか?特定の文字列だけに値の範囲を制限したくないですか? Lietral typesがあります。

例えばこういう関数が "hello" と "bye" だけを許したい場合には、

def greet(name: str, prefix: str = "hello") -> str:
    return f"{prefix} {name}!"

こう。

import typing_extensions as tx

Action = tx.Literal["hello", "bye"]


def greet(name: str, prefix: Action = "hello") -> str:
    return f"{prefix} {name}!"

ところでここで許可されていない値を渡すとmypyでエラーになります。

greet("hell", prefix="Go to")

"Go to" は "hello" でも "bye" でもないのでエラーです。こういうエラーが出ます。良いですね。

$ mypy --strict 03greet.py
03greet.py:10: error: Argument "prefix" to "greet" has incompatible type "Literal['Go to']"; expected "Union[Literal['hello'], Literal['bye']]"

ちなみに3.8以降はtyping_extensionsのinstallは不要でtypingに含まれます

ifの条件に。。(嬉しくない)

ところでLiteral typesをif文と一緒に使ってみましょう。

import typing_extensions as tx

Direction = tx.Literal["up", "down", "left", "right"]


def use(d: Direction) -> None:
    if d == "UP":  # not "up"
        return print("UUUUUUUUUUUUUUUUUUUU")
    else:
        return print("ELSE")

エラーになることを期待。。。

$ mypy --strict 04condition.py
Success: no issues found in 1 source file

おっと、成功してしまいました。かなしい。コレはかなしい。

ちなみにTypeScriptでは。良い感じに教えてくれます。

type Direction = "up" | "down" | "left" | "right";

function use(d: Direction){
  // こういうエラー
  // This condition will always return 'false' since the types 'Direction' and '"UP"' have no overlap.
  if (d == "UP") { // not "up"
    console.log("UUUUUUUUUUUUUUUUUUUUUUUUPPPPPPP");
  } else {
    console.log("ELSE");
  }
}

どうにかできないものでしょうか?

--strict-equality

ここで --strict-equalityオプションの出番です。

  --strict-equality         Prohibit equality, identity, and container checks for non-overlapping types (inverse: --no-strict-equality)

実行してみると良い感じにエラーが出てくれました。

$ mypy --strict --strict-equality 04condition.py
04condition.py:7: error: Non-overlapping equality check (left operand type: "Union[Literal['up'], Literal['down'], Literal['left'], Literal['right']]", right operand type: "Literal['UP']")
Found 1 error in 1 file (checked 1 source file)

やりましたね :tada:

まとめ

Literal typesのお供には--strict-equalityオプションを。