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

PythonのEnumをToStringしたい … シンボル名を文字列にしたい時のためのメモ

0
Last updated at Posted at 2025-09-11

enumなどのシンボル名を文字列にしたいことってないですか? (あります!)

C#では、ToStringメソッドをオーバーライドせずbaseクラスのそれが呼び出されると、オブジェクト名を文字列にして取得することができます。
ところが Pythonでは、locals() や globals() を使用した例の記事を見かけますが、それでは自分の要求を実現することができなかったので調査した結果のメモです。

from enum import IntEnum, auto
class ErrorID(IntEnum):
    MIN = 0   
    # 共通系
    INVALID_A = 1
    INVALID_B = auto()
    INVALID_C = auto()
    MAX = auto()

    def to_string(eid:ErrorID):
        d = dict()
        for e in ErrorID:
            d[e] = e._name_
        if (eid in d):
            return d[eid]
        return ""

print("to_string: ", ErrorID.to_string(ErrorID.INVALID_A))

結果:
to_string: INVALID_A

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