LoginSignup
0
1

More than 5 years have passed since last update.

Python3でEnumをいい感じに使う

Last updated at Posted at 2018-03-17

やりたいこと

python3で新たに追加されたEnumを利用して、いい感じに使いたい
例えば、以下の感じ

step = Step.init
step <- next_step
1番目のステップの処理を実行
step <- next_step
2番目のステップの処理を実行
...

コード例

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from enum import Enum
import sys

__author__ = "oomori"
__version__ = "1.0.0"

class Step(Enum):
    init = 0
    step1 = 1
    step2 = 2
    finish = 3

    def __iter__(self):
        return self.value

    def __next__(self):
        next_idx = self.value +1
        if next_idx < len(Step.__members__):
            # step2 = 2, step = 1と逆順で定義されている場合でも
            # value順になるように制御できるようにするため
            steplist = [ name for name, step in sorted(Step.__members__.items(), key=lambda x:x[1].value) ]
            next_name = steplist[next_idx]
            return Step.__members__.get(next_name)
        else:
            raise StopIteration

def main():
    step = Step.init
    while True:
        if step is Step.init:
            print('do somthin on step init')
        elif step is Step.step1:
            print('do somthin on step 1')
        elif step is Step.step2:
            print('do somthin on step 2')
        elif step is Step.finish:
            print('do somthin on step finish')
            break
        step = next(step)

if __name__ == "__main__":
    main()

Enum型なので、step = step +1とできるかと思ったら、TypeError: unsupported operand type(s) for +: 'Step' and 'int'とエラーになる
IntEnum型を利用できるんですが、pythonのドキュメントの注意に記載されている通り、
非推奨かつnameを取得できなかったので、上記のようにしてみました。

next(step)で次のステップにできるので、けっこう使い道はあるかなと。

参考

0
1
4

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