1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[python] 定義済みEnumから動的にEnumを生成する

Posted at

やりたいこと

定義済みのEnumから指定したリストで動的にEnumを生成する。

実装例

from enum import Enum

class Color(Enum):
    red = ""
    blue = ""
    yellow = ""
    purple = ""

    @classmethod
    def generate_enum(cls, target_list: list[str]):
        result = {e.name: e.value for e in cls if e.name in target_list}
        return Enum(__class__.__name__, result)

使用例

target_list = ["red", "purple"]
results = Color.generate_enum(target_list)
# results["red"], results("赤"), results["purple"], results("紫")が指定可能

説明

クラスメソッドgenerate_enum()で当該処理を担当。
自身の列挙値を一つずつ取り出し、引数で渡されたリストに存在しているか確認。
存在していれば{name: value}で格納。
格納値でEnumを再生成して返却。

参考記事

Python: Enumクラスを拡張する

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?