LoginSignup
3
0

More than 1 year has passed since last update.

Pythonのtyping.Literalの選択肢をlistとして渡す方法

Posted at

以下のように tuple を利用することでうまく定義できます.

from typing import Literal

choices = ["a", "b"]
choices_dict = {"a": 1, "b": 2}

Literal["a", "b"] == Literal[choices]
>>> False

Literal["a", "b"] == Literal[tuple(choices)]
>>> True

Literal["a", "b"] == Literal[choices_dict.keys()]
>>> False

Literal["a", "b"] == Literal[tuple(choices_dict.keys())]
>>> True

参考: Typing dynamically create literal alias from list of valid values

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0