LoginSignup
6
4

More than 3 years have passed since last update.

PythonでEnum

Last updated at Posted at 2018-01-26

Enumは標準モジュールです。

from enum import Enum, unique


@unique
class Game(Enum):
    action = "Action"
    rpg = "RPG"
    simulatoin = "Simulation"
    puzzle = "Puzzle"

使えているかチェック

>>> @unique
... class Game(Enum):
...     action = "Action"
...     rpg = "RPG"
...     simulatoin = "Simulation"
...     puzzle = "Puzzle"
... 
>>> Game.action
<Game.action: 'Action'>
>>> Game.rpg
<Game.rpg: 'RPG'>
>>> Game.rpg.value
'RPG'

以下のような使い方は、そのままでは出来ない。

>>> 'RPG' in Game
False

__members__ を利用すると解決できる。

from enum import Enum, unique


@unique
class Game(Enum):
    action = "Action"
    rpg = "RPG"
    simulatoin = "Simulation"
    puzzle = "Puzzle"

    @classmethod
    def values(self):
        return [e.value for e in self.__members__.values()]


>>> Game.values()
# ['Action', 'RPG', 'Simulation', 'Puzzle']
>>> 'RPG' in Game.values()
# True

値がINT型の場合はIntEnumも利用できますが、
以前の互換を維持するためや、Enumが上手くいかないケースでのみ利用を検討するべきと書かれています。

以下は、Color.redはenum型ですが、INT型との比較で同一と判定されている例です。

>>> from enum import IntEnum
>>> class Color(IntEnum):
...     red = 0 
...     yellow = 1 
...     blue = 2 
... 
>>> Color.red == 0
True
>>> Color.red.value == 0
True
>>> type(Color.red)
<enum 'Color'>
>>> type(Color.red.value)
<class 'int'>

IntEnumはIntのサブクラスなので、以下のようなことが起こる可能性があります。
よほどのことがない限り、この挙動は意図しないものなはずです。

>>> from enum import IntEnum
>>> class Color(IntEnum):
...     red = 0 
...     yellow = 1 
...     blue = 2 
...
>>> class Season(IntEnum):
...     spring = 0
...     summer = 1
...     autumn = 2
...     winter = 3
... 
>>> Season.summer == Color.yellow
True

楽しいEnumライフを。

6
4
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
6
4