0
1

python で int で値を入れつつ、json 化の際には文字列を使う Enum の作り方

Last updated at Posted at 2024-06-19
class Int2StrEnum(StrEnum):
    def __new__(cls, int_value, string_value):
        obj = str.__new__(cls, string_value)
        obj._value_ = string_value
        obj.int_value = int_value
        return obj

    @classmethod
    def from_int(cls, value: int):
        for member in cls:
            # noinspection PyUnresolvedReferences
            if member.int_value == value:
                return member
        raise ValueError(f"{value} is not a valid value for {cls.__name__}")


class A(Int2StrEnum):
   AAA = (1, "AAA(jsonで使う文字列)")
   BBB = (2, "BBB")
   CCC = (3, "CCC")

みたいに定義しておいて、

# 値をセットするとき
assert A.from_int(1) is A.AAA

# json.dumps のとき
json.dump({'a': A.AAA})  # そのまま渡せばいい
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