0
1

More than 1 year has passed since last update.

Enumを使って複数の定数文字列を管理する。

Last updated at Posted at 2022-10-15

2022/11/11 追記

StrEnumがPython11で実装されたのでそれも使いましょう。

Official Docs

Enumは複数の定数をクラスに纏めて管理できる

import enum

class Option(enum.Enum):
    A = "A"
    B = "B"
    C = "C"

my_choice = Option.A
print(my_choice)
# <Option.A: 'A'>

このように定義すると、Option.Aのように定数を呼び出すことができLiteralと違いタイプミスや、定数の値を間違えてもエラーとして検出できる。

Enumは文字列と比較できない

my_choice = Option.A
print(my_choice == "A")
# False

EnumはEnum.Valuesのインスタンスなので、文字列と比較するとFalseになる。

解決策

クラスを定義する際にstrを継承することで文字列と比較できるようになる。

import enum

class Option(str, enum.Enum):
    A = "A"
    B = "B"
    C = "C"

my_choice = Option.A
print(my_choice == "A")
# True
0
1
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
0
1